用于存储数组的字符串
String to store array
if(command=="insert")
{
int i=0;
while(i>=0)
{
string textToSave[i];
cout << "Enter the string you want saved: " << endl;
cin >>textToSave[i];
ofstream saveFile ("Save.txt");
saveFile << textToSave;
saveFile.close();
i++;
break;
}
}
我想把我输入的数组存储到。txt文件中。但我有问题,以创建数组存储。我也两难的选择之间的while循环和forloop,但认为while循环是更合适的,因为不知道多少时间需要插入单词。请帮助。谢谢。
您正在尝试存储整个字符串数组,而不仅仅是当前字符串。不知道为什么你需要i
和有一个数组,因为你只是读取和写入一个字符串的时间,无论如何。
可以是这样的:
if(command=="insert")
{
string textToSave;
cout << "Enter the string you want saved: " << endl;
cin >>textToSave;
ofstream saveFile ("Save.txt");
saveFile << textToSave;
saveFile.close();
break;
}
您遇到的一些最明显的问题是:
- 在声明
textToSave
时使用C99的一个称为变长数组的特性。这不是合法的c++。 - 如果可变长度数组声明有效,那么在获取用户输入 时,应该在最后一个索引之外写入一个。
- 在每次迭代中打开并覆盖文件。
- 你只循环一次,当你跳出循环时,所以无论如何只保存一个字符串。
- 如果你没有在循环结束时使用
break
,你将永远循环这个条件。
在循环之前创建数组,否则您将不断创建大小增加1的数组。如果您希望每个文件都保存在新文件中,请更改文件名,否则您会不断覆盖同一个文件。
string textToSave[string_count];
if(command=="insert")
{
int i=0;
while(i<string_count)
{
cout << "Enter the string you want saved: " << endl;
cin >>textToSave[i];
ofstream saveFile ("Save"+i+".txt");
saveFile << textToSave[i];
saveFile.close();
i++;
}
}
但我有问题创建数组来存储。
在循环外,声明一个空vector;这将保存数组:
vector<string> textToSave;
在循环中,读取一个字符串并将其附加到数组中:
string text;
cin >> text;
textToSave.push_back(text);
或者更简洁一点:
textToSave.push_back(string());
cin >> textToSave.back();
我也在while循环和forloop之间选择进退两难
看起来你根本不需要循环,因为你只是读取一个字符串。您可能需要一个外部循环来读取命令,沿着
行vector<string> textToSave;
for (;;) { // loop forever (until you reach "break")
string command;
cin >> command;
if (command == "quit") { // or whatever
break;
}
if (command == "insert") {
cout << "Enter the string you want saved: " << endl;
textToSave.push_back(string());
cin >> textToSave.back();
}
// other commands ...
}
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组