字符串输入
因为cin在读入字符串时,遇到空白字符(空格、制表符、换行符)会停止读取数据,为了解决为个问题,可以使用getline函数。
getline函数:getline(cin, inputLine);
其中 cin 是正在读取的输入流,而 inputLine 是接收输入字符串的 string 变量的名称。
1 2 3 4 5 6 7 8 9 10 11 12 | #include <iostream> #include <string> using namespace std; int main(){ string FullName; cout <<"Type your name: "; cin >>FullName; // get user input from the keyboard // getline(cin,FullName); cout <<"Your name is: "<<FullName<<endl; } |
使用getline函数输入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | include <iostream> #include <string> using namespace std; int main() { string str; cout << "Please enter your fullname: \n"; getline(cin, str); cout << "Hello, " <<str<<"welcome to Beijing !\n"; return 0; } |
getline可以加第三个参数,第三个参数为结束符号。
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> #include <string> using namespace std; int main() { string a; getline(cin,a,'.'); cout<<a<<endl; return 0; } |
fgets函数:
fgets 功能: 从输入流读取一整行(包括空格),最多读 n-1 个字符。
char* fgets(char* s, int n, FILE* stream);
特点:
| 特点 | 说明 |
|---|---|
| 读到换行符停止 | '\n' 也被存入 |
| 读到 n-1 个字符停止 | 自动加 '\0' |
| 可以读空格 | scanf("%s") 不行 |
| 返回 NULL | 表示读取失败/EOF |
适用场景:
✓ 输入含空格的一行文字 ✓ 读取文件内容逐行处理 ✓ 需要安全限制长度(防止缓冲区溢出)
不适用场景:
✗ 不知道行的最大长度(改用 getline) ✗ 只读单个数字/单词(用 scanf 更简洁) ✗ 需要读 std::string(用 getline(cin, s))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <cstdio> #include <cstring> int main() { char s[1000]; printf("请输入一行文字(含空格):\n"); fgets(s, sizeof(s), stdin); // 去掉末尾的 '\n'(fgets会把换行符也读进来) int len = strlen(s); if (s[len-1] == '\n') s[len-1] = '\0'; printf("你输入的是:%s\n", s); printf("长度:%d\n", (int)strlen(s)); return 0; } |
Quizzes
