C++ 读取多行带空格的字符串,以EOF结束

string s;
while(getline(cin,s)) {
    cout << s << endl;
}


输入eof:

windows——ctrl+z

unix/linux——ctrl+d

可以使用 scanf 函数读取并分隔字符串,存入字符串数组中。具体代码如下: ```c #include <stdio.h> #include <string.h> int main() { char str[100]; char strs[10][100]; int count = 0; printf("请输入字符串(以换行符结束):\n"); while (fgets(str, sizeof(str), stdin)) { str[strcspn(str, "\n")] = '\0'; // 如果输入的是空行,停止输入 if (strlen(str) == 0) { break; } // 将读取字符串存入字符串数组中 sscanf(str, "%s", strs[count++]); } // 输出存储的字符串 printf("输入的字符串为:\n"); for (int i = 0; i < count; i++) { printf("%d: %s\n", i + 1, strs[i]); } return 0; } ``` 当然,也可以使用 getchar 函数逐个字符读取并分隔字符串,存入字符串数组中。具体代码如下: ```c #include <stdio.h> #include <string.h> int main() { char ch; char str[100]; char strs[10][100]; int count = 0; printf("请输入字符串(以换行符结束):\n"); while ((ch = getchar()) != EOF) { if (ch == '\n') { // 如果输入的是空行,停止输入 if (strlen(str) == 0) { break; } // 将读取字符串存入字符串数组中 sscanf(str, "%s", strs[count++]); memset(str, 0, sizeof(str)); // 清空字符串缓冲区 } else if (ch == ' ') { // 将读取字符串存入字符串数组中 sscanf(str, "%s", strs[count++]); memset(str, 0, sizeof(str)); // 清空字符串缓冲区 } else { str[strlen(str)] = ch; } } // 输出存储的字符串 printf("输入的字符串为:\n"); for (int i = 0; i < count; i++) { printf("%d: %s\n", i + 1, strs[i]); } return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值