丢失读入的每一行输入中的最后一个令牌
Losing the last token from every line of input read in
我正在尝试编写一个程序,该程序将文件中的代码行作为字符串读取,然后将该字符串拆分为每个逗号周围的标记。(它是一个逗号分隔的文件(。
它在大多数情况下都有效,但我在每一行上都丢失了最后一个令牌。
//This is function splits input strings into tokens. It takes in an input
string
//and a delimiter character as parameters.
vector<string> tokenize(string inputString, char delimiter) {
//the store the delimiter in local variable
char newDelimiter = delimiter;
//store the input string in local variable
string newString = inputString;
//vector of strings to store tokens.
vector<string> tokenVector;
//temp variable for making tokens
string temp;
//iterate through the string...
for (int i = 0; i < newString.size(); ++i) {
//...checking for specified delimiter.
//If not present, add current character to temp string.
if (newString.at(i) != newDelimiter) {
temp += newString.at(i);
}
//if present, add temp string to vector and reset temp variable
else
{
tokenVector.push_back(temp);
temp = "";
}
}
return tokenVector;
}
int main() {
//string variable input will store each line of input
string input;
//use getline initially to "skip" the header line
getline(cin, input);
//this vector will be used to store each input lines string tokens
vector<string> stringTokens;
//this while loop will execute as long as cin is reading lines from the
file
while (getline(cin, input)) {
//print out each original line for testing purposes
cout << input << endl;
//split the string into tokens around commas
stringTokens = tokenize(input, ',');
//TEST OUTPUT
for (int j = 0; j < stringTokens.size(); ++j) {
cout << stringTokens.at(j) << " ";
}
cout << endl;
}
return 0;
}
输出的示例行:第二行缺少零。第一行只是原始字符串,第二行是输出:
1,000010007,01,XX,0,0,0,0,0,0,0,01 - XXXXX,XXXXXXXXXX,0,0,0,0,0,0,0,0,0,0,0
1 000010007 01 XX 0 0 0 0 0 0 0 01 - XXXXX XXXXXXXXXX 0 0 0 0 0 0 0 0 0 0
我该如何解决这个问题?谢谢。
循环后添加:
if (temp != "")
{
tokenVector.push_back(temp);
}
对于最后一个元素。
vector<string> tokenize(string inputString, char delimiter) {
...Code...
for (int i = 0; i < newString.size(); ++i) {
...Code...
}
if (temp != "") {
tokenVector.push_back(temp);
}
return tokenVector;
}
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在C++中,我如何接受不同于同一行的用户输入
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- 忽略一行输入中的某些输入
- 丢失读入的每一行输入中的最后一个令牌
- 一行输入到多个变量
- 如何检查从键盘输入的特定整数值是否存在于C++文件中的一行或多行中
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 与 C++ 中一行中的用户输入数组元素相关的问题
- 如何在应用程序进行大量printf时,在固定输入的终端中设置最后一行
- 使用 getline 从输入文件读取一行到输出文件
- 标准输入未读取最后一行
- C :使用getline从文本文件中输入,要么跳过第一行,要么将其余部分弄乱
- 在一行中输入具有其他输入类型的多个单词字符串
- 如何在用户输入值后写入.csv文件的下一行,而不会覆盖以前的值?
- 如何强制 getline() 一次输入一行
- 如何让控制台在输入一行文本时输出某些内容
- 在c++中一次向字符串数组中输入一行
- 程序只在文本文件中输入一行