我正在尝试编写代码,使用一个函数从 stdin 读取 42 个字符串,并知道我保存了多少个字符串。 这是我到目前为止的想法:
#define rows 42
#define chars 101
void populate(int* citiesCount, char cities[][chars]);
int main()
{
char cities[rows][chars]; //array of strings to store all lines of txt file
int citiesCount = 0; //how many lines there really are (may be less than 42)
populate(&citiesCount, cities);
//print all cities
printf("NUMBER OF CITIES: %d\n", citiesCount);
for(int i = 0; i < citiesCount; i++)
{
printf("CITY: %s\n", cities[i]);
}
printf("END\n");
return 0;
}
void populate(int* citiesCount, char cities[][chars])
{
char cntrl;
for(int i = 0; i < rows; i++)
{
printf("%d\n", *citiesCount);
scanf("%100[^\n]", &cities[*citiesCount++]); //read line of txt file and save it to array of strings
printf("%s\n", cities[i]);
cntrl = getchar(); //check, if I'm at end of file, if yes break loop
if(cntrl == EOF)
break;
}
}
代码由以下语句编译
gcc -std=c99 -Wall -Wextra -Werror proj1.c -o proj1
在这个项目中,禁止使用动态内存分配。
如果我尝试编译代码,我会收到以下错误:
“'%[^' 需要 'char *' 类型的参数,但参数 2 的类型为 'char (*)[101]'”
我尝试了所有可能的方法来处理它,但找不到任何有效的方法。
最佳答案
如果你不太热衷于使用 scanf 这个应该会有所帮助
void populate(int* citiesCount, char cities[][chars])
{
for(int i = 0; ( i < rows ) && fgets( cities[i], chars, stdin) ; i++)
{
// remove there if not required.
printf("%d\n", (*citiesCount)++ );
printf("%s\n", cities[i]);
}
}
关于c - 如何通过 C 中的函数操作字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47121042/