你好我正在写一个程序,现在从文件中读取值。打印出额外的数字? (C)
它在数值读取,通过与fgets 字符串,然后我想改变其中一个字符串为整数:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#define FILSIZE 1024
typedef struct _node
{
unsigned int uid;
char *uname;
struct _node *next;
} *node;
int main(int argc, char* argv[])
{
FILE *pFile; // pointer file
char currentLine[FILSIZE];
bool isListEmpty = true;
node firstNode = NULL;
printf("\n\nargc: %d\nargv[0]: %s\nargv[1]: %s\n\n", argc, argv[0], argv[1]);
if(argc == 1)
{
pFile = stdin;
}
else if (argc == 2)
{
char buffer [50];
sprintf(buffer, "%s.txt" ,argv[1]);
printf("%s", buffer);
pFile = fopen(buffer, "r");
}
if(pFile == NULL)
{
printf("Not working");
exit(0);
}
int i=1;
int nameCounter = 1;
int colonCounter=0;
while(!feof(pFile) && fgets(currentLine, sizeof(currentLine), pFile))
{
unsigned int nameLength;
unsigned int tempuid;
unsigned int idstorlek;
node firstNode = malloc(sizeof(struct _node));
char *temporaryString;
temporaryString = strtok(currentLine, ":");
colonCounter=colonCounter+1;
//printf(" fungera pls");
printf(" %d Namnordning %s \n", nameCounter, temporaryString);
nameLength = strlen(temporaryString);
firstNode->uname = malloc((nameLength+1) * sizeof(char));
strcpy(firstNode->uname, temporaryString);
printf("NAMNET: %s \n", temporaryString);
while(temporaryString != NULL)
{
printf(" %s \n", temporaryString);
if(colonCounter == 3)
{
int tempuid=atoi(temporaryString);
// idstorlek = sizeof(tempuid);
// firstNode->uid = malloc(4);
printf(" IDN: %d \n", tempuid);
firstNode->uid = tempuid;
printf("firstNodeid %d", firstNode->uid);
}
temporaryString = strtok(NULL, ":");
colonCounter=colonCounter+1;
}
if(colonCounter == 6)
{
// printf("FUNGERAR ID: %d NAMN %s \n", tempuid, firstNode->uname);
}
printf("%d Row is done \n", i);
i=i+1;
nameCounter = nameCounter+1;
colonCounter = 0;
}
}
但是,当我把它写出来,我得到:
1 Namnordning mr
NAMNET: mr
mr
x
1171
IDN: 1171
firstNodeid 1171 1101
Mikael R�nnar
/Home/staff/mr
/usr/local/bin/tcsh
1 Row is done
2 Namnordning axelsson
NAMNET: axelsson
axelsson
x
12856
IDN: 12856
firstNodeid 12856 1101
Bj�rn Axelsson
/Home/staff/axelsson
/usr/local/bin/tcsh
2 Row is done
3 Namnordning gabriel
NAMNET: gabriel
gabriel
x
16928
IDN: 16928
firstNodeid 16928 1101
Gabriel Jonsson
/Home/staff/gabriel
/usr/local/bin/tcsh
3 Row is done
4 Namnordning set
NAMNET: set
set
x
12037
IDN: 12037
firstNodeid 12037 1101
Set Norman
/Home/staff/set
/usr/local/bin/tcsh
4 Row is done
5 Namnordning dahlin
NAMNET: dahlin
dahlin
x
12928
IDN: 12928
firstNodeid 12928 1101
Fredrik Dahlin
/Home/staff/dahlin
/usr/local/bin/tcsh
5 Row is done
6 Namnordning fahlgren
NAMNET: fahlgren
fahlgren
x
17847
IDN: 17847
firstNodeid 17847 1101
Daniel Fahlgren
/Home/staff/fahlgren
/usr/local/bin/tcsh
6 Row is done
为什么我也会在那里得到1101? 其他tempuid部分只给我正确的ID。 我没有找到正确的内存吗? (我一直在尝试,它只给我奇怪的错误,与idsize部分)。
嗨,乔。欢迎来到堆栈溢出!请稍后阅读介绍[游览]。你可以[编辑]你的问题,并为这个语言添加一个标签? – usr2564301
是的,它在C中,我添加了它。不知道你应该这样做:) – Joe
@Joe发布相关的代码。 – ameyCU