gpt4 book ai didi

C++从文档中读取两行内容,存入两个变量

转载 作者:行者123 更新时间:2023-11-30 03:55:49 26 4
gpt4 key购买 nike

我正在尝试打开一个“.txt”文件并读取第一行的内容和第二行的内容。在“.txt”文件的两行上有一些数字用简单的“空格”分隔。

如何从第一行读取内容并将每个数字保存在x[100]中,以及从第二行读取内容并将每个数字保存在y[100]中?

PS:我是初学者

#include<iostream>
#include<fstream>
using namespace std;
int main() {
int x[100], y[100], i=0;

ifstream myfile("something.txt");

while(myfile >> x[i]) {
cout << x[i] << "\n";
i++;
}
return 0;
}

非常感谢!

最佳答案

按照评论中的建议,使用 std::getlinestd::istringstream

std::string line1;
std::getline( myfile, line1 );
std::istringstream s( line1 );
while( i < 100 && s >> x[i] )
{
cout << x[i] << endl;
++i;
}
// Bail out if i == 100 and s is not empty.

// Same for line2 and y (and different i)

(备注:代码替换了您的 while 循环。)

关于C++从文档中读取两行内容,存入两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28873120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com