![](/img/trans.png)
[英]how to ignore/skip white spaces when reading from a textfile using string getline in c++
[英]How to read in a string with spaces in C++ without using getline
我的輸入文件如下:S New York 25 76 49
我想閱讀它們,其中S是字符,而New York是字符串或cstring,其他3是整數。 我的問題是在紐約讀書,我不能使用getline,因為3個整數緊隨其后,而不是換行。 我能做什么?
我建議使用正則表達式來解析輸入。 已添加到C ++ 11 <regex> C ++參考中的標准庫
有關Wikipedia的更多詳細信息: C ++中的正則表達式
您的另一種選擇是一次讀取一個字符,只要字符isalpha()
或isspace()
后跟另一個isalpha()
,就將該字符存儲在字符串中。 例如:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main (void) {
char c, last = 0;
string s;
while (cin.get(c)) { /* read a character at a time */
/* if last is alpha or (last is space and current is alpha) */
if (last && (isalpha(last) || (isspace(last) && isalpha(c))))
s.push_back(last); /* add char to string */
last = c; /* set last to current */
}
cout << "'" << s << "'\n";
}
使用/輸出示例
$ echo "S New York 25 76 49" | ./bin/cinget
'S New York'
它可能不像正則表達式那么優雅,但是您始終可以通過簡單地遍歷輸入的每個字符並挑選出所需的內容來解析所需的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.