简体   繁体   English

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

[英]How to read txt file C++ and split them into columns

This is the first time i am writing code in c++ (Visual studio 2010) . 这是我第一次用C ++(Visual Studio 2010)编写代码。 I have the logic i want to implement but i cannot put it to code. 我有要实现的逻辑,但我无法将其写入代码。 Have looked on many samples but nothing found. 看了很多样本​​,但没有发现。

Basically i have a tab delimited txt file and i want to read it and put the data into string,string array anything. 基本上我有一个制表符分隔的txt文件,我想读取它并将数据放入字符串,字符串数组中的任何东西。

The issue is using the built in : 问题是使用内置的:

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

Will put the data into string array but splitting the row by Space even if the space occurs in the data row it will break it into two columns which is the problem. 将数据放入字符串数组,但即使数据行中出现空格,也按空格将行拆分,这会将其分为两列,这就是问题所在。

How can i properly read data line by line and into columns using c++ ? 如何使用c ++正确地逐行和逐列读取数据?

If your column data may contain spaces, better use " around string or add '\\t' as delimiter. 如果您的列数据可能包含空格,则最好在字符串周围使用"或添加'\\t'作为分隔符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM