简体   繁体   English

从txt文件获取变量

[英]getting variables from txt file

I have little code problem..Someone have any idea what could be wrong? 我的代码问题很少。有人知道什么地方可能出问题了吗?

my code: 我的代码:

FILE *tiedosto;
char tiedostonimi[] = "input.txt";
tiedosto = fopen (tiedostonimi, "r");
char luokka, kaupunki[4];
int kuutio, vuosi, kuukausi, paiva;

fscanf(tiedosto, "%i&energialuokka=%c&kaupunki=%s&Vuosi=%i&Kuukausi=%i&pva=%i", &kuutio, &luokka, &kaupunki, &vuosi, &kuukausi, &paiva);
printf("%d %c %s %d %d %d , kuutio, luokka, kaupunki, vuosi, kuukausi, paiva);

line inside txt file: txt文件中的一行:

22&energialuokka=A&kaupunki=ei&Vuosi=2010&Kuukausi=02&pva=22

("22" "A" "ei" "2010" "02" "22" are not permanent values.. given via website form and saved into text file) (“ 22”,“ A”,“ ei”,“ 2010”,“ 02”,“ 22”不是永久值。通过网站表单给出并保存到文本文件中)

Current 当前

OUTPUT IS: 输出是:

22 u ei&Vuosi=2010&Kuukausi=02&pva=22 831192666 0 -163754450

When scanning in a C-"string" do not use the address-of operator ( & ). 扫描C字符串时,请勿使用地址运算符( & )。

So this line: 所以这行:

fscanf(tiedosto, "%i&energialuokka=%c&kaupunki=%s&Vuosi=%i&Kuukausi=%i&pva=%i", &kuutio, &luokka, &kaupunki, &vuosi, &kuukausi, &paiva);

should be like this: 应该是这样的:

fscanf(tiedosto, "%i&energialuokka=%c&kaupunki=%s&Vuosi=%i&Kuukausi=%i&pva=%i", &kuutio, &luokka, kaupunki, &vuosi, &kuukausi, &paiva);

The background to this is, that if using the array variable without index operator it (already) decays to the pointer to (the address of) its first element. 这样做的背景是,如果使用不带索引运算符的数组变量,它(已经)衰减到指向其第一个元素(其地址)的指针。

The problem is that when scanning for a string, the scanf family of function will scan until a whitespace (or end of file, whichever happens first). 问题在于,当扫描字符串时,函数scanf系列将扫描到空格(或文件结尾,以先发生者为准)。 You can't really use pattern-matching when scanning for a string. 扫描字符串时,您实际上不能使用模式匹配。 You can verify this quite simply by checking the return value of fscanf , in your case it should be 3 (since it scans the integer, a character and then the rest as a single string). 您可以通过检查fscanf的返回值来非常简单地验证这一点,在您的情况下,返回值应该为3 (因为它将扫描整数,一个字符,然后将其余部分扫描为单个字符串)。

Incidentally this will of course lead to undefined behavior as you overwrite the array allocated for the string by quite a margin, as well as you printing the values of uninitialized local variables. 顺便说一句,这将导致不确定的行为,因为您将为字符串分配的数组覆盖相当大的余量,并且还会打印未初始化的局部变量的值。

Instead it might be better to tokenize the input (hint: see the strtok function), to first split it on the ampersand '&' , and except the first value then split the other on the equality character '=' . 相反,它可能会更好来标记输入(提示:见strtok函数),以第一分割它在符号'&' ,并且除了所述第一值然后分裂另一个在平等字符'=' Then check each "key" to know what value to set. 然后检查每个“键”以了解要设置的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM