不知何故,当我运行这段代码并输入字符串时,第一个 i=0 的字符串被跳过,它开始从 A[1] 输入字符串。所以我最终得到了 A[0] ,其中充满了内存中的随机内容。有人可以指出问题所在吗?
cin>>s;
char** A;
A = new char *[s];
cout<<"now please fill the strings"<<endl;
for (int i=0;i<s;i++)
{
A[i] = new char[100];
cout<<"string "<<i<<": ";
gets(A[i]);
}
最佳答案
那个代码太可怕了。在真正的 C++ 中它应该是这样的:
#include <string>
#include <iostream>
#include <vector>
int main()
{
std::cout << "Please start entering lines. A blank line or "
<< "EOF (Ctrl-D) will terminate the input.\n";
std::vector<std::string> lines;
for (std::string line; std::getline(std::cin, line) && !line.empty(); )
{
lines.push_back(line);
}
std::cout << "Thank you, goodbye.\n";
}
注意没有任何指针或 new
表达式。
如果您愿意,可以通过添加 std::cout << "> " &&
来添加一点提示打印在 for
条件检查的开头循环。
关于c++ - 字符串数组中的第一个字符串被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13941775/