【发布时间】:2012-03-01 00:36:01
【问题描述】:
有人可以帮我解决这个问题吗?我有一个.txt 文件,我正在通过fopen 使用C 读取该文件,如下所示。我可以将文本作为变量显示到屏幕上,这很好。但是,我从文件中读取的文本是逗号分隔的。如何将文本文件中的字符串拆分为两个变量而不是一个?
示例
用户名、密码
我希望最终输出是
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。此外,在这种情况下,fgets比fscanf更合适,因为在这里使用它可能会导致缓冲区溢出。 -
在条件和
{之间添加注释是一种惯例,如if (condition) /* here */ {。 C 编译器不介意。你的人类观众可能会觉得它很不寻常,因为它很不寻常。 -
如果是 C 应用程序,为什么还要包含
iostream? -
谁能帮我回答这个问题。这样我就可以包含系统(“暂停”)功能。只使用 C 6 天。