只想知道如何從包含空格的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;
}
爲什麼要用''\ b''替換每個非空格字符? –
'getline()'可能適合你 – Stephen
在關於C的問題中顯示C++程序令人困惑。你應該真的有兩個問題 - 兩個不同的問題。一個應該是關於爲什麼你的C++不工作。另一個人應該儘可能在C程序上盡力而爲,並解釋爲什麼它不起作用。你應該可以使'fgets()'工作來讀取行,而不管行內的空白。 –