简体   繁体   English

如何在不使用getline的情况下在C ++中读取带空格的字符串

[英]How to read in a string with spaces in C++ without using getline

my input file looks like this : S New York 25 76 49 我的输入文件如下:S New York 25 76 49

i want to read them where S is a character and New York is either a string or a cstring and the other 3 are integers. 我想阅读它们,其中S是字符,而New York是字符串或cstring,其他3是整数。 My problem is reading in New York i cant use getline since the 3 integers come after it and not in a new line. 我的问题是在纽约读书,我不能使用getline,因为3个整数紧随其后,而不是换行。 What can i do? 我能做什么?

I would suggest using Regular Expressions to parse the input. 我建议使用正则表达式来解析输入。 Added to the standard library in C++ 11 <regex> C++ reference 已添加到C ++ 11 <regex> C ++参考中的标准库

More details on wikipedia: Regular Expressions in C++ 有关Wikipedia的更多详细信息: C ++中的正则表达式

Your other option is simply to read a character at a time and as long as the character isalpha() or isspace() followed by another isalpha() , store the character in your string. 您的另一种选择是一次读取一个字符,只要字符isalpha()isspace()后跟另一个isalpha() ,就将该字符存储在字符串中。 For example: 例如:

#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";
}

Example Use/Output 使用/输出示例

$ echo "S New York 25 76 49" | ./bin/cinget
'S New York'

It may not be as elegant as a regex, but you can always parse what you need simply by walking through each character of input and picking out what you need. 它可能不像正则表达式那么优雅,但是您始终可以通过简单地遍历输入的每个字符并挑选出所需的内容来解析所需的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM