文章
2
粉丝
0
获赞
2
访问
252
对于输入数据,cin
是 C++ 中最常用的输入方法,但它默认会忽略空格和换行符(将其作为分隔符)。
getline
可以从输入流中读取一整行内容,包括空格。它通常用于读取字符串。
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
cout << "Enter a string with spaces: ";
getline(cin, input); // 读取整行,包括空格,第一个参数写cin,第二个参数写要传入的变量,第三个参数可以写读到什么符号结束,也可以不写。
cout << "You entered: " << input << endl;
return 0;
}
cin.get()
可以读取单个字符,包括空格和换行符。
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Enter a character (including space): ";
ch = cin.get(); // 读取一个字符,包括空格和换行符
cout << "You entered: " << ch << endl;
return 0;
}
cin.getline()
可以读取一行字符,包括空格,并将其存储到字符数组中。
#include <iostream>
using namespace std;
int main() {
char input[100];
cout << "Enter a string with spaces: ";
cin.getline(input, 100); // 读取一行,包括空格
cout <...
登录后发布评论
暂无评论,来抢沙发