我想将几个字符串(名称)写入指针数组。我写了一个代码,我想逻辑上会这样做,但由于某种原因,它只打印最后一个字符串。有什么可以解决这个问题的?使用getline将字符串读入指针数组(C)
#include <stdio.h>
#include <stdlib.h>
#define MAX 50
int jatekosell(char* s) {
int n, ok = 1;
n = atoi(s);
if(n<3 || n > 15)
{
printf("Nem jo! 3 es 15 koze kell essen!");
getline(s, MAX);
ok = 0;
}
return ok;
}
int getline(char *s, int n);
void main() {
char amount[MAX];
char name[MAX];
char *names[MAX];
int number, i, j;
printf("Number of players between 3 and 15: ");
getline(amount, MAX);
while(!jatekosell(amount));
number = atoi(amount);
for(i = 0; i < number; i++)
{
printf("Type the %d. name: ", i+1);
getline(name, MAX);
names[i] = name;
}
for(i = 0; i < number; i++)
{
printf("The names: %s\n", names[i]);
}
getchar();
}
int getline(char *s, int n){
int c;
char *t=s;
while(n-- > 0 && (c=getchar())!=EOF&&c!='\n') *t++ = c;
*t='\0';
while(c!=EOF&&c!='\n') c=getchar();
return(t-s);
}
已经有一个'getline'函数是标准库的一部分。你应该为你的函数真的使用另一个名字(比如'getln')? –
当它确实看起来非常像'fgets(,, stdin)''时,是否有理由甚至使用该getline? –
另外['int main()'](http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c),对我来说这看起来像你不编译随着警报的启用... –