如何读取txt文件C ++并将其拆分为列 [英] How to read txt file C++ and split them into columns

查看:60
本文介绍了如何读取txt文件C ++并将其拆分为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次用c ++(Visual Studio 2010)编写代码.我有要实现的逻辑,但我不能将其编写为代码.查看了许多样本,但未找到任何内容.

This is the first time i am writing code in 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.

基本上我有一个制表符分隔的txt文件,我想读取它并将数据放入字符串,字符串数组中的任何内容.

Basically i have a tab delimited txt file and i want to read it and put the data into string,string array anything.

问题是使用内置的:

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.

如何使用c ++正确地逐行和逐列读取数据?

How can i properly read data line by line and into columns using c++ ?

推荐答案

如果您的列数据可能包含空格,则最好在字符串周围使用"或添加'\ 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];
}

这篇关于如何读取txt文件C ++并将其拆分为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆