visualstudio2010-如何读取txt文件C++并将其拆分为列
visual studio 2010 - How to read txt file C++ and split them into columns
这是我第一次用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];
}
相关文章:
- C++将向量的向量拆分为向量的N个子向量
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- OpenCV 4.1.2 - 从网络摄像头获取帧并将其拆分
- 使用 C++ 将命令行参数拆分为参数/向量
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 如何在C++中将数字拆分为数字
- 在线程之间拆分任务总是值得的吗?
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 在 c++ 中拆分类和标头中的继承,错误
- 在矢量内拆分 deques
- 拆分重叠段
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 通过空行提升拆分字符串
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 如何按多个括号类型拆分字符串,但仍将括号保留在C++?
- 将 Boost.Spirit.X3 解析器拆分为多个 TU
- 将字符串拆分为等长 c++ 的部分
- 将执行循环拆分为多个线程 (1-N-1-N-1..)
- 使用范围拆分string_view
- 将 std::大小为 m 的向量拆分为大小为 n 的向量