不知何故,当我运行此代码并且输入字符串时,跳过第一个字符串,其中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]);
}
Run Code Online (Sandbox Code Playgroud)
那段代码太可怕了.以下是它在真正的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";
}
Run Code Online (Sandbox Code Playgroud)
注意没有任何指针或new表达式.
如果您愿意,可以通过std::cout << "> " &&在for循环中的条件检查开始时添加一些提示打印.