c++中用什么输入方式可以将一个带空格的东西逐个输入a112
在C++中,可以使用cin输入流和getchar()函数来逐个输入带空格的字符串。以下是两种方法的示例代码:
方法一:使用cin输入流
#include <iostream>
using namespace std;
int main() {
char a[112];
cout << "Enter a string with spaces: ";
cin >> noskipws; // 不跳过空格
int i = 0;
while (cin >> a[i]) {
if (a[i] == ' ') {
break;
}
i++;
}
a[i] = '\0'; // 在最后添加空字符,表示字符串的结束
cout << "The string you entered is: " << a << endl;
return 0;
}
方法二:使用getchar()函数
#include <iostream>
using namespace std;
int main() {
char a[112];
cout << "Enter a string with spaces: ";
int i = 0;
char c;
while ((c = getchar()) != ' ' && c != '\n') {
a[i] = c;
i++;
}
a[i] = '\0'; // 在最后添加空字符,表示字符串的结束
cout << "The string you entered is: " << a << endl;
return 0;
}
这两种方法都可以逐个输入带空格的字符串,并将结果存储在字符数组a中
原文地址: http://www.cveoy.top/t/topic/h5q5 著作权归作者所有。请勿转载和采集!