C如何拆分从.txt文件scanf读取的变量

标签 c string split scanf

有人可以帮我解决这个问题吗?我有一个 .txt 文件,我正在使用 C 通过 fopen 读取它,如下所示。我可以将文本作为变量显示到屏幕上,这很好。但是,我从文件中读取的文本是逗号分隔的。如何将文本文件中的字符串拆分为两个变量而不是一个变量?

例子

用户名,密码

我希望最终输出是

var1 = 用户名 var2 = 密码

这是我的代码。

inFile = fopen("logfile.txt", "r"); /*This opens the file */    
if (inFile == NULL)            /*Checks that the file exists*/ {        
    printf("\nThe file %c was not opened successfully.", fileName);     
    printf("\nPlease check that you entered the file name correctly.\n");       
    exit(1);    
}   
while (fscanf(inFile, "%s", text) !=EOF) /*Reads and displays the file*/        
    printf("%s\n", text);   
fclose(inFile);

修复的种类

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

int main (void) { 
    char *s; 
    char test[50];
    int i=0;
    char str[] = 
        "username,password";
    printf ("%s\n", str); 
    s = strtok (str, ","); 
    // 
    while (s != NULL) { 
        printf ("%s\n", s); 

        s = strtok (NULL, ","); 

} 
        system("pause");
    return 0; 

} 

最佳答案

strtok 函数就是您要查找的内容

关于C如何拆分从.txt文件scanf读取的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9508995/

相关文章:

python - 为什么功能不起作用?试图替换字符串中的单词

java - java的split string方法也可以返回带分隔符的数组

Java 拆分和替换字符串

c - 在 Msp430 上使用 4 位气泡显示

c++ - 为什么在定义宏 ## 操作时有 2 层间接寻址

c - 寻求开箱即用的基于 Windows 的 C 单元测试系统(最好使用 Netbeans)

python - 如何以编程方式从十六进制中检索 unicode 字符?

c - 获取终端光标位置

r - 提高在大字符串向量上计算词分数总和的性能?

linux - 如何使用 linux 将一个文件分割成多个不同行的文件?