【发布时间】:2018-08-03 01:48:27
【问题描述】:
所以我正在处理一个需要读取的文件,其中包含逗号分隔单词和每行末尾的回车换行符,但我无法找到处理它的方法。我正在尝试在逗号之前读取每个单词并将其放入 a 向量中,直到它到达回车换行符,但我遇到了问题。
这是我的文本文件(在notepad++上可以看到符号。在实际文本中,[]里面的东西没有出现)
microwave,lamp,guitar,couch,bed,dog,cat[cr][lf]
P1:microwave,couch,bed,dog,chair,bookcase,fish[cr][lf]
我尝试了多种解决方案,但似乎没有任何效果。这是我到目前为止所尝试的。但它显然不起作用。我看到一些用户建议使用 substring 以某种方式读出逗号,并读入单词,但我不知道该怎么做。我找不到一个好的教程或示例。在我的脑海中,我有算法(或至少,如何去执行它的步骤),但我不确定如何去实现它。
Import file (istream)
Read until comma, take string and place it in vector1 (getline, input, ,), vector.push_back(input)
Repeat previous step until you reach \cr\lf stop reading. (getline(input, '/r'))
move on to the next line
Read until comma, take string and place it in vector2
Repeat
Read the line until /cr/lf
这是我使用上述部分步骤实践的代码。
string input;
vector<string> v1;
vector<string> v2;
ifstream infile;
infile.open("example.txt");
while(getline(infile, input)) //read until end of line
{
while(getline(infile, input, '\r')) //read until it reaches a carriage return
{
while(getline(infile, input, ',')) // read until it reaches a comma
{
v1.push_back(input); //take the word and put in vector.
}
}
}
infile.close();
任何帮助将不胜感激。
编辑:我忘了提。当我使用这段代码时,它似乎没有将任何东西导入向量中。我确信所有单词都在 getline 函数的某个地方丢失了,但我不知道如何在不使用它的情况下只读取逗号和回车换行符。
【问题讨论】:
-
您不必担心
\cr\lf对,因为Windows应该会自动将它们转换为单个\r。因此std::getline应该做正确的事。只关心行和逗号。 -
@Galik — 对,但
’\r’是一个错字。应该是’\n’,即换行符。 -
@PeteBecker 它匹配代码中的 cmets :) \r 是回车符,\n 是换行符。