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

visual studio 2010 - How to read txt file C++ and split them into columns

本文关键字:C++ 拆分 文件 txt 何读取 读取 visualstudio2010-      更新时间:2023-10-16

这是我第一次用c++(Visual studio 2010)编写代码。我有我想要实现的逻辑,但我不能把它写进代码中。我看了很多样品,但一无所获。

基本上,我有一个tab分隔的txt文件,我想读取它并将数据放入字符串、字符串数组中。

问题是使用内置的:

ifstream in;
in.open("someData.txt");
while(!in.eof())//the text from the file is stored in different variables
   {
   in>>inputData[0];
   in>>inputData[1];
   }

将数据放入字符串数组,但按空格分隔行,即使数据行中出现空格,也会将其拆分为两列,这就是问题所在。

如何使用c++正确地逐行将数据读入列中?

如果列数据可能包含空格,最好在字符串周围使用"或添加't'作为分隔符。

您可以按如下所示对代码进行重新排序,以确保最后不会读取空行。

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

或者,如果任何一行中第二列的条目丢失,情况会更好。

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];
}