C++文件输入从下一行开始
C++ File Input start from next line
我必须编写一个程序来读取这样的文件:
7
5 6 4 2 1 3 8
第一行表示有多少人,第二行表示每个人的身高。我设法读取了第一行并存储在一个变量中,但我如何才能继续到第二行单独读取每个整数(它们用空格分隔)
using namespace std;
int rowNum;
int main()
{
fstream myfile;
string rowNumT;
myfile.open ("xxx_in.txt",ios::in | ios::out);
if(myfile.is_open()){
while(getline(myfile,rowNumT)){
//cout << rowNumT ;
istringstream (rowNumT) >> rowNum;
cout << rowNum ;//how many children in integer form
}
}
else cout << "Unable to open file";
int heights[rowNum];
myfile.close();
return 0;
}
无需解析字符串和额外高度,使用简单:-
int npeople ;
int height ;
// std::vector<int> heights ; // Use std::vector
myfile >> npeople ;
while ( myfile >> height )
{
// Use height ;
// heights.push_back ( height );
}
或
myfile >> npeople ;
std::vector<int> heights ;
std::copy( std::istream_iterator<int>( myfile ),
std::istream_iterator<int>(),
std::back_inserter( heights )
) ;
此外,还可以使用C++11实现以下功能:
myfile >> npeople ;
std::vector<int> heights { std::istream_iterator<int>( myfile ),
std::istream_iterator<int>()
};
一种读取&存储第二行(从第一行获取编号后)。
std::ifstream infile("file.txt");
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int n;
std::vector<int> v;
while (iss >> n)
{
v.push_back(n);
}
}
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 如何从头开始创建 avi 文件?
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 自一周开始以来的秒数?
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 一旦双簧管录制开始,主 UI 线程就会被阻止
- GStreamer在开始任何播放之前进行搜索
- 为什么如果我添加这一行,我的程序会不断询问值
- gvim 换行应该结束当前字符串并在下一行开始一个新的字符串
- C++文件输入从下一行开始