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

问题描述

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

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;
}

尽管我真的不知道它的用法,所以您应该根据自己的目的进行调整。