如何从包含空格的 stdin 输入字符串
how to input a string from stdin which contains whitespaces?
只是想知道如何从包含空格的 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 也应该按原样正确读取行。
相关文章:
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 当使用带有stdin和stdout重定向的双进程管道时,如何避免stdin上的重复输入
- 将两个独立的stdin重定向为程序的输入
- 如何使用低级系统调用从 stdin 和输入文件中获取字节数
- 检查不作为单个条目的STDIN输入
- 如何将数据写入 stdin,以便由等待来自 stdin 输入的单独线程使用?
- C 程序需要STDIN的输入,但我想从Shell脚本中输送/发送这些输入
- C++以缓冲速率从STDIN读取输入
- 如何从包含空格的 stdin 输入字符串
- 如何获取类似 QIODevice 的控制台输入信号 (stdin)
- 从重定向的stdin获取输入时使用seekg()
- 为什么在 stdin 上输入时"n"而不是从代码输入时显示不同?
- 使用 select() 使用 UDP 套接字从多个对等方接收,同时从 STDIN 获取用户输入
- C++文件分析器/stdin输入-这个算法会起作用吗
- QTextStream stdin读取行未暂停输入
- c++getline似乎无法识别通过管道传输到stdin的输入中的换行符
- 循环以丢弃来自stdin、Linux C++的虚假变量输入
- 在Linux上,在Eclipse CDT中使用gdb调试C++应用程序,以及如何向stdin输入内容
- 将字符数组输入stdin
- 使用stdin重定向输入