从 .txt 文件中读取多种数据类型,其中一个字符串有空格 C++ [英] Reading In Multiple Data types from a .txt file where one of the strings has spaces C++
问题描述
我有一个看起来像这样的文本文件:
I have a text file that looks like this:
汽车,CN,819481,维修,假,无
Car, CN, 819481, maintenance, false, NONE
汽车,SLSF,46871,商业,真实,孟菲斯
Car, SLSF, 46871, business,true, Memphis
汽车,AOK,156,温柔,真实,旧金山
Car, AOK, 156, tender, true, San Francisco
(逗号实际上是制表符,但我无法在此站点上正确设置它们的格式)
(the commas are tabs in actuality, but I was unable to get them to format properly on this site)
我有一个名为 Car 的对象,我正在将代码读入并使用代码底部的输出进行输出.我当前的代码可以读取所有前 5 种数据类型,但我无法读取最后一列可能有空格的内容.我曾尝试使用 getline,但无济于事.
I have an object called Car which i am reading the code into and outputting using the output at the bottom of the code. My current code can read in all of the first 5 data types, but I am having trouble with reading in the last column where there can be spaces. I have tried using getline, but to no avail.
这是我将txt作为输入的函数的代码
Here is the code that I have for the function that takes the txt as inputs
void input()
{
ifstream inputFile;
inputFile.open("input.txt",fstream::in);
if (inputFile.fail())
{
cout<<"input failed"<<endl;
exit(1);
}
string type;
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
while(inputFile.peek() != EOF)
{
inputFile>>type>>reportingMark>>carNumber>>kind>>loaded;
while(inputFile.peek() == ' ')
inputFile.get();
getline(inputFile, destination);
Car temp(reportingMark, carNumber, kind, loaded, destination);
temp.output();
}
inputFile.close();
}
推荐答案
不要使用>>
操作符,使用getline
:
Don't use >>
operator, use getline
:
string line;
while (getline(inputFile, line) {
// split line by tabs or commas
}
分割函数示例:
vector<string> explode(string &str, char separator) {
vector<string> result;
string tmp;
for (int i = 0; i < str.size(); i++) {
if (str[i] == separator) {
result.push_back(tmp);
tmp.clear();
} else tmp += str[i];
}
if (tmp.size() > 0)
result.push_back(tmp);
return result;
}
我希望 std::vector
对你来说不难.示例加载代码(而不是 while(inputFile.peek() != EOF) { ... }
):
I hope that std::vector
isn't hard for you. Example loading code (instead while(inputFile.peek() != EOF) { ... }
):
string line;
while (getline(inputFile, line) {
vector<string> data = split(line, '\t'); // Or use ASCII code 9
if (data.size() != 5) {
cout << "Invalid line!" << endl;
continue;
}
Car temp(data[0], data[1], stoi(data[2]), data[3], data[4]);
temp.output();
}
不要复制粘贴此代码,我看到您有未处理的 bool 变量等.
Don't copy-paste this code, I see that you have bool variables etc. that is not handled.
这篇关于从 .txt 文件中读取多种数据类型,其中一个字符串有空格 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!