我收到一个错误:
错误:将数组类型赋值给表达式
在这个程序中,应该打印有4-8个字母的单词:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char rec[300];
int zbroj1=0, br=0, zbroj2=0;
while((rec=getchar()) != '\n')
{
zbroj1++;
}
if(zbroj1>=4 || zbroj1<=8)
printf("Nova recenica je: %s", zbroj1);
return 0;
}我怎么才能解决这个问题?
发布于 2018-09-06 12:46:24
下面是打印大小为>= 4和<= 8的单词的代码
#include<stdio.h>
int main(void) {
char rec[9]; //you may need to adjust the buffer according to the size of the words
int br=0, zbroj2=0;
while((zbroj2=getchar()) != '\n') {
if(br < 8)
rec[br] = zbroj2; // we are not going to store the words having length more than 8
br++;
if(zbroj2 == 32){
if(br>4 && br<=8){
rec[br] = '\0';
printf("Nova recenica je: %s\n", rec);
}
br = 0;
}
}
if(br>=4 && br<=8){ // This check is to catch the last word
rec[br] = '\0';
printf("Nova recenica je: %s\n", rec);
}
return 0;
}发布于 2018-09-06 12:06:45
这就是错误的来源..。
rec=getchar()...as rec是char的数组,getchar()以int的形式返回字符。使用未使用的变量br来存储返回值,使用计数器变量zbroj1作为索引存储到数组中,可以使用以下代码构建rec:
while((br=getchar()) != '\n')
{
rec[zbroj1]=br;
zbroj1++;
}C中的字符串需要在结尾处有一个\0字符来终止它们,所以您还需要有行来完成它
rec[zbroj1]='\0';然后,检查长度的代码有一个逻辑错误--它使用的是||,这意味着两个表达式都必须为true,并且要打印出一个字符串,因此您希望使用&& (和)来确保zbroj1包含在4-8之间。
if(zbroj1>=4 && zbroj1<=8)最后,输出一个字符串,但传递一个int。要打印出这个单词,您需要传入在rec中构建的字符串
printf("Nova recenica je: %s", rec);将所有这些更正组合在一起,您将得到代码的最终版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char rec[300];
int zbroj1=0, br=0, zbroj2=0;
while((br=getchar()) != '\n')
{
rec[zbroj1]=br;
zbroj1++;
}
rec[zbroj1]='\0';
if(zbroj1>=4 && zbroj1<=8)
printf("Nova recenica je: %s", re);
return 0;
}发布于 2018-09-06 12:09:05
有两个问题。第一个是getchar()的返回值。这
rec=getchar()当然会引起警告,因为getchar()返回类型是int,而不是rec类型。来自getchar()的手册页
int getchar(无效); 返回值
getchar()在文件或错误结束时将读取为无符号字符的字符返回给int或EOF。
其次,使用逻辑-或||的逻辑或||作为&&打印rec,如果zbroj1在4和8之间,即当两种条件都为真时,例如
if(zbroj1>=4 && zbroj1<=8)工作代码
#include<stdio.h>
int main(void) {
int ret;
char rec[300];
int zbroj1=0, br=0, zbroj2=0;
while((ret=getchar()) != '\n') {
rec[zbroj1] = ret; /* you need to store into array */
zbroj1++;
}
rec[zbroj1] = '\0'; /* terminate the array with \0 */
if(zbroj1>=4 && zbroj1<=8) /* use logical && */
printf("Nova recenica je: %s", rec); /* use %d as zbroj1 is of int type*/
return 0;
}https://stackoverflow.com/questions/52203587
复制相似问题