首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++有没有办法让GetLine读取由空格分隔的一行中的两个数字?

C++有没有办法让GetLine读取由空格分隔的一行中的两个数字?
EN

Stack Overflow用户
提问于 2020-04-17 18:18:15
回答 3查看 58关注 0票数 0

我需要我的程序来读取这些数字:

代码语言:javascript
复制
4
42 5
47 6

这是我到目前为止所得到的:

代码语言:javascript
复制
//5sk3u
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int f,d,s; //f=4, d=42, then 47, s=5, then 6
    string line;
    ifstream myf ("Data.txt");
    (getline (myf,line));
    f=std::stod (line);
    getline (myf,line);
    d=std::stod(line);
    getline (myf,line);
    s=std::stod(line);
    cout << f << endl;
    cout << d << endl;
    cout << s;         //I'll make a loop for the final program, but right now this part isn't working
}

我不明白如何用s=5代替s=47。我是新手,通过阅读其他解决方案,我无法理解任何东西,因为有太多的新信息。什么是最简单的方法来做这件事,接近我现有的代码?谢谢你的帮助。

编辑:这是我的任务。“鸡在市场上出售。鸡的数据写在文件"Data.txt”中,待售鸡的数量在第一行,随后的几行显示鸡的质量和年龄。编写一个程序,在结果文件“Results.txt”中查找并打印原始鸡的数据。“结果需要看起来像这样:"Chicken numbr.1: numbr.1:42 age:5“,对于所有的鸡都是如此。

EN

回答 3

Stack Overflow用户

发布于 2020-04-17 18:23:48

如果这是一些在线问题解决程序,不要把它搞得过于复杂。你就这样读吧:

代码语言:javascript
复制
int main()
{
     int n, age, mass;
     std::ifstream chickensFile("Data.txt");
     chickensFile >> n;

     for(int i=0; i < n; ++i) {
         chickensFile >> mass >> age;
         std:cout << "Chicken numbr: "<< /* do it yourself */;
     }

     return 0;
}
票数 0
EN

Stack Overflow用户

发布于 2020-04-17 18:32:02

您可以像这样从文件中读取用空格分隔的单词:

代码语言:javascript
复制
    ifstream file("Data.txt");
    std::string word;
    while (file >> word)
    {
        std::cout<< word << '\n';
    }
票数 0
EN

Stack Overflow用户

发布于 2020-04-17 20:11:59

我问我的朋友,我们一起做了这个:

代码语言:javascript
复制
int a,x,z,n,f,j;
fstream fd;
fd.open ("Duomenys.txt");
n=0;
f=0;
j=z+1;
fd >> a;
while (n<a){
fd >> x >> z;
cout << x << " " << z << endl;
if (x>f){f=x;}
if (z<j){j=z;}
n++;}
cout << f << endl;
cout << z;

问题解决了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61269202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档