且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何读取txt文件C ++并将其拆分为列

更新时间:2022-12-12 16:56:35

如果您的列数据可能包含空格,则***在字符串周围使用"或添加'\ t'作为分隔符.

If your column data may contain spaces, better use " around string or add '\t' as delimiter.

您可以重新排列代码以使其使用,如下所示,以确保您最终不会读取空行.

You can reorder your code to use as shown below to ensure you don't read an empty line at last.

ifstream in("someData.txt");
while(in>>inputData[0])
{
   in>>inputData[1];
}

如果在任何行中缺少第二列的条目,甚至更好.

Or even better if entry of second column in any line is missing.

std::string line;
while(getline(std::cin,line))
{
  // Splitting into 2 in case there is no space
  // If you colum may contain space, replace below lines with better logic.
  std::istringstream iss(line);
  inputData[0] = inputData[1] = default_value;
  iss >> inputData[0] >> inputData[1];
}