本文介绍了如何在一行结尾处停止读取输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不同类型的n个输入列表我希望从文件中读取:


例如:

string string int int double double int int int double ...

我的输入文件在一行上给出它的值,用空格分隔

或制表符。

但是,只给出了这些值的第一个k
变量并在到达行尾时停止阅读?


谢谢!

解决方案




读取整行(使用''getline'')到std :: string对象然后

使用std :: istringstream解析它。


V





当你到达行尾时为什么要停止阅读?

结束-0f-line字符[sequence]是就C ++而言,只是另一个空格

。它会在下一行的开头找到k + 1值




I have a list of n inputs of varying type I wish to read from a file:

For example:
string string int int double double int int int double ...

My input file gives its values on a single line, separated by spaces
or tabs.
However, only the first k<=n of these values are given. Without
knowing beforehand what k is, how do I read these k values to my
variables and stop reading when I reach the end of the line?

Thanks!

解决方案



Read the entire line (using ''getline'') into std::string object and then
parse it using std::istringstream.

V




Why should you stop reading when you reach the end of the line?
The end-0f-line character [sequence] is just another whitespace
as far as C++ is concerned. It will find the k+1 value
at the beginning of the next line.




This will read every value into a string. It is up to you to convert it
to the right type.

If you know in advance what the type of your data is (fixed string
string int int....), you can use the same technique, substituting s1 for
the correct variable in which you want to store the values.

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

int main()
{
std::ifstream file( <full-path-her> );

std::string line;
std::istringstream parser;

if(file)
{
std::string value;
while( std::getline(file, line) )
{
parser.clear();
parser.str(line);

while(parser)
{
parser>>value;
std::cout<<"NextValue: "<<value<<std::endl;
}
}
}
return 0;
}


这篇关于如何在一行结尾处停止读取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:10
查看更多