gpt4 book ai didi

c - 在 C 中使用结构类型打印字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:57:26 25 4
gpt4 key购买 nike

我正在处理结构类型。我从我自己的文件中取出一行,上面写着“cerberus guards the river styx”。当我尝试打印出来时,只打印出字母“c”。我不知道为什么会这样。

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

typedef unsigned int uint;

struct wordType
{
char word[80];
uint count;
};

struct wordType words[10];

int main( void ) {
FILE * inputFile;
char * line = NULL;
size_t len = 0;
ssize_t read;
uint index;
inputFile = fopen( "input.txt", "r");

if( inputFile == NULL )
{
printf( "Error: File could not be opened" );
/*report failure*/
return 1;
}

index = 0;
while( ( read = getline( &line, &len, inputFile ) ) != -1 )
{
printf( "%s\n", line );
*words[index].word = *line;
printf("line = %s\n", (words[index].word) );
}

free( line );
return 0;
}

最佳答案

*words[index].word = *line;

line[0] 复制到 words[index].word[0] 中,因此只有一个字符。如果你想复制整行,你必须使用

strcpy(words[index].word, line);

但是你应该验证这条线是否合适,即

strlen(line) < 80

在那之前。

关于c - 在 C 中使用结构类型打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16267410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com