C++ 字符串 數組
C++ 求助字符串數組从键盘输入: i am 19 years old有什么好的方法可以做到把上面的这一 带空格的字符串放
C++ 求助 字符串 數組 从键盘输入: i am 19 years old 有什么好的方法可以做到把上面的这一 带空格的字符串放到数组日a[ ]中 像这样: a[0]=i a[1]=am a[2]=19 a[3]=years a[4]=old 简单的,别太难啊 我是c++菜鸟,望各位大师能帮个忙.. [解决办法]
char a[10][80]; int i = 0; while(scanf("%s", a+i++)) ; [解决办法] std::vector<std::string> words;
std::string word;
while(std::cin >> word) words.push_back(word);
[解决办法] #include <stdio.h>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
char buf[255] = "";
char cResult[10][10];
gets(buf);
int i = 0;
int first = 0, second = 0;
char c;
while ((c = buf[i]) != '\0')
{
if (c != ' ')
{
cResult[first][second] = c;
++second;
}
else
{
cResult[first][second] = '\0';
++first;
second = 0;
}
++i;
}
cResult[first][second] = '\0';
for (int i = 0; i < first; i++)
{
std::cout << cResult[i] << std::endl;
}
std::system("pause");
return 0;
}
[解决办法] gets函数就可以了。楼上的方法可以试一下。
[解决办法] 引用: std::vector<std::string> words; std::string word; while(std::cin >> word) words.push_back(word); 正解,既然学c++,就用STL吧。用一个元素类型为string的vector就搞定了,cin会自动忽略空格的
[解决办法] for (int i = 0; i <= first; i++)
{
std::cout << cResult[i] << std::endl;
}
[解决办法] 引用: std::vector<std::string> words; std::string word; while(std::cin >> word) words.push_back(word); 这个是最简单明了的了