#include "iostream"using namespace std;int main(){char *p[5] ;for (int i = 0; i < 5; i++){p[i] = (char *)calloc(100, sizeof(char));}cout << "please input an number such as \"one hundred"" and twenty five\"" << endl;for (int i = 0; i <= 5; i++){char ch = cin.get();while (ch != ' ' || ch != '\0'){*p[i]++ = ch;ch = cin.get();}if (ch == '\0') break;}for (int i = 0; i < 5; i++){cout << p[i];}return 0;}我想从键盘输入到一段字符串,然后将这段字符串从空格处拆分开到一个指针数组里面,知道字符串结尾现在我我输入 one hundred and twelve 的时候老是不成功请高手帮我看下
1 回答
跃然一笑
TA贡献1826条经验 获得超6个赞
1、cin.get函数不会接收到'\0'这种字符,输入回车后结束输出,因此接收到的应该是'\n'。
2、while的循环条件,ch != ' ' || ch != '\n'(这里换成\n),不等于空格或者不等于回车,那这不就是永远为真的?应该是&&吧。
3、*p[i]++ = ch; p的指针已经被++了,后面还怎么能当做cout的首地址呢。
应该改成这个样子吧
char *p[5] ; char *q; for ( int i = 0; i < 5; i++) { p[i] = ( char *) calloc (100, sizeof ( char )); } cout << "please input an number such as \"one hundred" " and twenty five\"" << endl; for ( int i = 0; i <= 5; i++) { q = p[i]; char ch = cin.get(); while (ch != ' ' && ch != '\n' ) { *q++ = ch; ch = cin.get(); } if (ch == '\n' ) break ; } for ( int i = 0; i < 5; i++) { cout << p[i]; } |
- 1 回答
- 0 关注
- 267 浏览
添加回答
举报
0/150
提交
取消