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

how to input a string from stdin which contains whitespaces?

本文关键字:stdin 输入 字符串 空格 包含      更新时间:2023-10-16

只是想知道如何从包含空格的 stdin 中获取字符串?我尝试了 fgets 和 scanf("%[^]",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;
}
#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;
}

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

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

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

cin >> t;

在第一次调用 getline 之前,尾随换行符将保留在输入缓冲区中。这个问题在回答这个问题时得到了解释:cin.getline(( 跳过了C++中的输入 - 以及许多重复项。但是,即使您不解决这个问题,在第一行之后,getline 也应该按原样正确读取行。