用于存储数组的字符串

String to store array

本文关键字:字符串 数组 存储 用于      更新时间:2023-10-16
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 ...
}