-5
#include <stdlib.h>
#include <string.h>

int main(void){
double sum=0;
int ii=0;
char buf[256], token[100]; // I am making this "finite length". You need to know how long the line is that you allow...

printf("Enter the numbers to average on a single line, separated by space, then press <ENTER>\n");
gets(buf, 255, stdin);
token = strtok(buf, " ");
while(token != NULL) {
sum += atof(token);
ii++;
token = strtok("", " "); // get next number
}
printf("AVERAGE: ***** %lf\ *****", sum / (double)ii);
return 0;
} 

它给出了这个错误 - 第 9 行:stdin undeclared & 当我添加 stdio.h 头文件时,它给了我错误 - 第 11 行:预期左值

任何人都可以纠正它吗?

4

4 回答 4

2

token应该是指针而不是数组

所以更换

char token[100]

经过

char *token;

并替换此行

token = strtok("", " "); // get next number

经过

token = strtok(NULL, " "); // get next number
于 2013-10-08T14:11:16.487 回答
0

您应该包括头文件stdio.h

当我添加 stdio.h 头文件时,它给了我错误 - 第 11 行:预期左值

token是不可修改的l-vlue。你不能修改它。
一种可能的解决方案是声明一个指针token_ptr并分配strtok.

char buf[256], token[100]; // I am making this "finite length". You need to know how       long the line is that you allow...
char *token_ptr ;
printf("Enter the numbers to average on a single line, separated by space, then press  <ENTER>\n");
gets(buf, 255, stdin);
token_ptr = strtok(buf, " ");
 .....
于 2013-10-08T14:08:05.767 回答
0

token是一个数组,数组名称是一个不可修改的左值。

以下对象类型是左值,但不是可修改的左值:

An array type
An incomplete type
A const-qualified type
An object is a structure or union type and one of its members has a const-qualified type

您需要一个指向 char 的指针。strtok返回指向在字符串中找到的最后一个标记的指针。

所以这:

char buf[256], token[100]; 

应该是这样的:

char buf[256], *token; 

这也是不正确的:

gets(buf, 255, stdin);

它应该是:

fgets(buf, 255, stdin);

您更正的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
double sum=0;
int ii=0;
char buf[256], *token; // I am making this "finite length". You need to know how long the line is that you allow...

printf("Enter the numbers to average on a single line, separated by space, then press <ENTER>\n");
fgets(buf, 255, stdin);
token = strtok(buf, " ");
while(token != NULL) {
sum += atof(token);
ii++;
token = strtok("", " "); // get next number
}
printf("AVERAGE: ***** %lf\ *****", sum / (double)ii);
return 0;
} 
于 2013-10-08T14:10:22.453 回答
0

token是不能分配给的数组名。你需要一个char *p_token来替换它。

于 2013-10-08T14:09:51.463 回答