有人可以帮我解决这个问题吗?我有一个 .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/