如何从包含空格的stdin输入字符串?

时间:2016-05-01 04:22:35

标签: c++ input whitespace

只是想知道如何从stdin中获取包含空格的字符串?我尝试了fgets和scanf("%[^ \ n]",str),但它仍无法在C中工作。

我尝试用程序从c ++中的给定字符串中删除空格。 这是我的代码,但它不起作用。

#include <iostream>
#include <string>
using namespace std;

int main() {
    // your code goes here
    int t;
    cin >> t;
    while (t--) {
        char s[1000];
        cin.getline(s, 1000);
        // cout<<s;
        int i;
        for (i = 0; s[i]; i++) {
            if (s[i] != ' ')
                s[i] = '\b';
        }
        for (i = 0; s[i]; i++)
            cout << s[i];
        // cout<<endl;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string getInput( string input )
{
    getline( cin, input );

    return input;
}

// Handles tabs and spaces
string removeWhitespace( string input )
{
    input.erase( remove_if( input.begin(),
                            input.end(),
                            []( char ch ){ return isspace( ch ); } ),
                 input.end() );

    return input;
}

int main()
{
    cout << removeWhitespace( getInput( {} ) ) << endl;

    return 0;
}

答案 1 :(得分:0)

您的代码已经在读取带空格的行。这就是getline的作用。奇怪的是,你有这个循环

for (i = 0; s[i]; i++) {
  if (s[i] != ' ')
    s[i] = '\b';
}

将用'\b'替换所有可见字符,这是退格字符,并且在大多数终端中不可见。如果删除该循环,则代码几乎正常。唯一剩下的问题是,对于循环的第一次迭代,您将无法输入任何内容,因为这一行:

cin >> t;

在第一次调用getline之前,尾随换行符将保留在输入缓冲区中。在这个问题的答案中解释了这个问题:cin.getline() is skipping an input in C++ - 以及许多重复的问题。但是,即使你没有解决这个问题,在第一行之后,getline应该正确地读取行。