如何在C ++中处理多个用户参数?

问题描述

Task Commands Picture好吧,我在以前的工作中取得了一些进步,但是我无法克服这个问题,因为问题可能并不大。我的任务基本上是一个文本文件编辑器,在程序开始运行后需要多个用户参数,范围从例如“详细信息”之类的1到具有display xy或savepart xy之类的随机用户输入的3或4(请参见附件) 。我的代码当前在用户使用cin和getline输入的第一行中,但是它只能读取已知的字符串,例如load userinput.txt(即文件名),然后退出,并且我不知道如何存储用户输入的内容变量的值。我该如何解决

基本上可能需要更改的是while循环下的getline或if语句中写的内容,但是我已经尝试了一切。

#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>

using namespace std;
string secondword;
string fword;
string line;
ifstream myfile;
fstream fFile;
bool running = true;
int x;
int length;

int main(int argc,char* argv[]) {

    
    while (running) {   
        getline(cin,fword);    //Reads first line user inputs

        //if first word equals laod command load file to memory
        if (fword == "load userinput.txt") {
           ifstream myfile("userinput.txt",ifstream::binary);

            myfile.seekg(0,myfile.end); //Searches till end of file
            length = myfile.tellg();    //Sets length as total number of chars in file
            myfile.seekg(0,myfile.beg); //Searches from the beginning

            char* buffer = new char[length];   //Allocates file memory to pointer

            cout << "Reading " << length << " characters... " << endl;
            myfile.read(buffer,length); //reads file and compares buffer size with legnth size
            if (myfile)
                cout << "All characters read and stored in memory sucessfully" << endl;
            else
                cout << "error: only " << myfile.gcount() << " can be read" << endl;;
            myfile.close();
        }
 
        //Quit
        if (fword == "quit") {
            running = false;    //Breaks while loop statement
            cout << "User has quit the program" << endl;
        }
        
        //Clear all lines in text
        if (fword == "clear all") {
            fFile.open("userinput.txt",ios::out | ios::trunc);
            fFile.close();
            cout << "All lines have been cleared" << endl;
        }

        //display All Text
        if (fword == "display text") {
            myfile.open("userinput.txt",ios::in);
            while (getline(myfile,line)) { //read data from file object and put it into string.
                cout << line << endl; //print the data of the string
            }
        }

    }

    return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)