ifstream file;
file.open("Data.txt");
string name;
string names[5];
string weight;
string weights[5];
int skip = 3;
int count = 0;
int count2 = 0;
int index[5] = { 1, 2, 3, 4, 5 };
int user;
while (file >> names[count]) //While the file goes through the txt file and collects 5 names
{
for (int i = 0; i < skip; i++)
file >> name; //For each time i is less that 3, then output the names read from the file to the console
count++;
}
file.close();
file.open("Data.txt");
file.ignore(5);
while (file >> weights[count2]) //While the file goes through the txt file and collects 5 names
{
for (int i = 0; i < skip; i++)
file >> weight; //For each time i is less that 3, then output the names read from the file to the console
count2++;
}
for (int j = 0; j < 5; j++) {
cout << index[j] << ". " << "Name: " << names[j] << ", " << "Current Weight(KG): " << weights[j] << '\n'; //Output all of the files collected and stored in the names array
}
file.close();
int choice;
int newWeight;
cout << "Which index would you like to change?" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "You have chosen index " << choice << " which is " << names[choice - 1] << " who weighs " << weights[choice - 1] << "KG" << endl;
cout << "Please enter the user's new weight" << endl;
cin >> newWeight;
weights[choice] = newWeight;
file.open("Data.txt");
cout << "Changed" << endl;
file.close();
break;
}
所以我有一个文本文件,其中存储了有关5个用户的详细信息:名称,体重,以前的体重和身高。我试图通过获取用户的输入来更新用户在文件中的权重。因此,如果用户在txt文件中的权重为90,并且用户输入了95,那么我想将文件中的权重从90更改为95]
程序已经读取了重量和用户名,所以我只需要知道如何在文本文件中替换重量即可。
ifstream文件; file.open(“ Data.txt”);字符串名称;字符串名称[5];弦重字符串权重[5]; int skip = 3; int count = 0; int count2 = 0; int index [5] = {1,2,3,4,5}; int用户;而(...
据我所知,您不能覆盖磁盘上文件中的特定行。您将必须读取整个文件并将其存储在内存中,然后根据用户输入对值进行调整,然后重新创建文件并将结果写入磁盘,从而覆盖之前的文件。