我用Visual Studio 2012创建了一个简单的项目,代码编译成功,运行,打印结果如我所料(水果名称:apple)。当我尝试用 gcc 编译相同的代码时,打印输出看起来不同(水果名称是:apple')。 ' 来自哪里?下面是代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * getCharValue(char line[]){
char *pch = strchr(line, '='); //find where the equal sign is in the line
char *pch1 = strchr(line, '\0'); // find the index of the end of the line
char *info = (char *) malloc(sizeof(char) * (pch1-pch-4));
info[pch1-pch-5] = '\0';
// copy the value to a new array then return the new char;
memcpy(info, &line[pch-line+3], pch1-pch-5);
return info;
}
int main()
{
char nameFileName[] = "Name.txt"; //register file name;
char *nameValue;
FILE *fid = fopen(nameFileName, "r");
if (fid != NULL){
char line[150];
while(fgets(line, sizeof(line), fid) != NULL){
//if this line is not empty or a comment line
if ((strncmp(line, "//", 2) != 0) && (line[0] != '\n')) {
if (strstr(line, "fruit_name") != NULL){
nameValue = getCharValue(line);
printf("The fruit name is: %s\n", nameValue);
}
}
}
}
else{
printf("Can not find the input file.");
exit(-1);
}
fclose(fid);
return 0;
}
文本文件仅包含 1 行:
fruit_name = 'apple'
我的代码有什么问题吗?为什么它与 Visual Studio 一起工作没有问题,但使用 gcc 却不能产生正确的结果?
最佳答案
您已使用 '
进行分隔,但从不检查它们,也从不检查格式错误的文件。这是我的修订版。请注意,我不转换 malloc()
也不使用 sizeof(char)
。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * getCharValue(char line[]){
char *pch, *pch1, *pch2, *info;
int len;
pch = strchr(line, '='); // find where the equal sign is in the line
if (pch == NULL)
return NULL;
pch1 = strchr(pch+1, '\''); // find the following quote mark
if (pch1 == NULL)
return NULL;
pch2 = strchr(pch1+1, '\''); // find the following quote mark
if (pch2 == NULL)
return NULL;
// copy the value to a new array then return the new char;
len = pch2 - pch1 - 1;
if (len <= 0)
return NULL;
info = malloc(len+1);
memcpy(info, pch1+1, len);
info[len] = '\0';
return info;
}
int main()
{
char nameFileName[] = "Name.txt"; //register file name;
char *nameValue = NULL; //default
FILE *fid = fopen(nameFileName, "r");
if (fid != NULL){
char line[150];
while(fgets(line, sizeof(line), fid) != NULL){
//if this line is not empty or a comment line
if ((strncmp(line, "//", 2) != 0) && (line[0] != '\n')) {
if (strstr(line, "fruit_name") != NULL){
nameValue = getCharValue(line);
if (nameValue == NULL)
printf("The file was badly formatted\n");
else
printf("The fruit name is: %s\n", nameValue);
}
}
}
}
else{
printf("Can not find the input file.");
exit(-1);
}
fclose(fid);
free(nameValue); // won't matter if it is NULL
return 0;
}
程序输出
The fruit name is: apple
关于c - 字符串在 Visual Studio 和 gcc 中的打印方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32194068/