[英]C++ string not concatenating char when int even though it is a char
這是我的可運行代碼:
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char **argv) {
if (argc > 1) { // passed in parameter
ifstream file(argv[1]); // create file from second parameter
string line;
if (file) { // file exists and has been opened
//stack *stmt = new stack();
while (getline(file, line)) { // run through lines of file
string word = "";
cout << "LINE: " << line << endl;
for (int i = 0; i < line.length(); i++) { // run through char of line
char ch = line[i];
if (ch == ' ') {
if (word == "") {
continue;
} else {
//stmt->push(word);
cout << "\x1b[34;1mWORD: " << word << "\x1b[0m" << end;
word = "";
}
} else {
word += ch;
}
}
}
cout << stmt->size() << endl;
while (stmt->has_next()) {
cout << stmt->pop() << endl;
}
} else {
cerr << "\x1b[31;1mNo such file, \x1b[21m" << argv[1] << "\x1b[0m" << endl;
}
} else { // no parameters passed in
cerr << "\x1b[31;1mYou did not specify any files to parse\x1b[0m" << endl;
}
return 0;
}
看起來很簡單。 但是,當字符ch
是整數(例如'0'
到'9'
)的字符時,根本不會附加該字符。
你們會發生這種情況嗎(如果您像這樣創建測試文件:
this is from line 1
line 2
3
然后在g++ test.cpp
-如果您將文件test.cpp
和./a.out test
如果您將上述測試文件存儲為要進行test
-您將(令人沮喪地)看到WORD: ...
(藍色) )如果數字是單個字符,則永遠不包含數字。
IE OUTPUT
對我來說:
LINE: this is from line 1
WORD: this
WORD: is
WORD: from
WORD: line
LINE: line 2
WORD: line
LINE: 3
這非常令人沮喪。 請幫助並解釋為什么它不起作用或評論它對您有用。
似乎只有在單詞后面有空格時才打印單詞:
if (ch == ' ') {
....
cout << "\x1b[34;1mWORD: " << word << "\x1b[0m" << end;
....
}
給定測試中的數字不是這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.