使用 getchar 从文件中读取字符串

问题描述

试图创建一个可以执行 bash 命令的 C 程序,我试图通过从文本文件中读取命令来做到这一点。我遇到的问题是 getchar 非常适合读取 1、2、3 等单个字符,但我很难获得一个以上字符的字符串。

我的代码:

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


// the only variables that are used
char choice;
char str[50],dirName;
int i;
int finished = 1;

while(finished) {

printChoice(); // only prints to terminal [1] to cd [2] to exit prog

choice = getchar();
dirName = getchar();
 
switch(choice){
    case ('1'):
        while(dirName !='\n') { // im sure i've placed this while loop in the wrong place but I dont know any better
            str[i] = dirName;
            i++;
            dirName = getchar(); 
        }

        printf("Enter directory you'd like to move into: ");
        changeDir(str); // function to cd
        break; 

    case ('2'): // exit program
        printf("Closing Program...\n");
        finished=0;
        break;

    default: // incorrect user choice
        printf("Invalid choice\n\n");
        break;
    }
}
    
return 0;}

我正在尝试读取的文本文件输入(如果我只用 1 2 运行程序,则程序按预期工作):

1 Documents 2

所需的输出:

cd Documents // once finished
exit program

解决方法

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

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...