C++如何使用argv[1]读取第一个用户参数,并将其存储在字符串中以读取/写入文本文件



我的任务是制作一个C++程序,用于读取、写入、保存、加载和附加文本文件。到目前为止,我有两个问题一直困扰着我。第一个问题是,如何使用argv将用户输入的第一个参数存储在字符串中?其次,我如何创建程序,以便当用户输入命令时,程序不会立即退出,因此从技术上讲,在收到退出消息之前,一直处于一个短暂的循环中?我已经尝试过这样做了,但我的代码也进入了循环。

int main(int argc, char* argv[]) {
while (!inFile.eof()) {
inFile.open("userinput.txt");
getline(cin, line);
if (argc > 1) {
int result = strcmp(argv[1], "load");
if (result == 0) {
cout << "CORRECT" << endl;
}
else{
exit(1);
}
}
}
return 0;
}

类似的东西,读取程序参数,读取用户输入,读取/写入/附加文件。

#include <iostream>
#include <ios>            // new
#include <fstream>        // new
using namespace std;
int main(int argc, char* argv[]) 
{
fstream inFile("userinput.txt", std::ios_base::app | std::ios_base::out); //new, allows to append lines to 'userinput.txt'
while (!inFile.eof()) {
string line;
getline(cin, line);
inFile << line;  // new: write the user input on inFile
if (argc > 1) {
int result = strcmp(argv[1], "load");
if (result == 0) {
cout << "CORRECT" << endl;
}
else {
exit(1);
}
}
}
return 0;
}

不过我真的不知道这个词的用法,所以你应该根据自己的目的来调整它。

最新更新