字符串输入: cin
、scanf()
、gets()
、getchar()
、getline()
、cin.get()
、cin.getline()
…
字符串输出: cout
、printf
、puts()
…
gets()
函数用于从标准输入流中读取字符串,直到遇到换行符或文件结束符为止,并将其存储在指定的字符数组中。它不检查输入字符串的长度,可能导致缓冲区溢出,因此不建议使用。
getchar()
函数用于从标准输入流中读取一个字符,并返回该字符的ASCII码值。
char ch;
cout << "Enter a character: ";
ch = getchar();
cout << "You entered: " << ch << endl;
cin.get()
函数用于从输入流中读取一个字符,但无法读取空白字符(例如空格、制表符等)。
getline()
函数用于从输入流中读取一行文本,并将其存储在字符串对象中。它能够处理空格并在遇到换行符时停止。
string line;
cout << "Enter a line: ";
getline(cin, line);
cout << "You entered: " << line << endl;
cin.getline()
函数用于从输入流中读取一行文本,并将其存储在字符数组中,可指定读取的最大字符数,以防止缓冲区溢出
char str[50];
cout << "Enter a string: ";
cin.getline(str, 50);
cout << "You entered: " << str << endl;
当前需要使用字符数组和指定最大读入字符的时候建议使用cin.getline()
puts()
输出的字符串必须以\0
结尾,否则会出错。而且它的输出的自带换行的,适合输出简单字符串。
puts("hello");
puts("world");
char a[10] = {"你好"}; // 输出字符数组
puts(a);
输出
hello
world
你好