2012-07-07 153 views
1

我寻求一位c编程专家。提前致谢。fgets中的包装函数()

例子:

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

void main() 
{ 
char name[100][52],selection[2]="Y"; 
int x,nname=1; 
float sales; 

do 
{ 
    printf("Enter name: "); 
    fflush(stdin); 
    fgets(name[nname],51,stdin); // i need put a wrapper in here 
    printf("Enter sales: "); 
    scanf("%f",&sales); 
    if (sales<1000) 
     printf("%s\tgood\n",name[nname++]); 
    else 
     printf("%s\tvry good\n",name[nname++]); 
    printf("Enter another name?(Y/N)"); 
    fflush(stdin); 
    fgets(selection,2,stdin); 
    *selection=toupper(*selection); 
}while(nname<=100 && *selection=='Y'); 
for(x=1;x<nname;x++) 
    printf("%s\n",name[x]); // want print the result without(newline) /n 

printf("END\n"); 
system("pause"); 
} 

如何打印名称,而不由新线分开?

+0

代码编译我的机器 – 2012-07-07 12:28:15

+0

是啊,我知道,我想打印的结果是这样的: '名1名2 name3'它只是在我编辑了编码线 – Wilson 2012-07-07 12:30:59

回答

1

只需使用的

printf("%s ", name[x]); 

代替

printf("%s\n", name[x]); 

\n字符创建新的生产线。

编辑

fgets显然换行符读入缓冲区 - 你可以去除换行与

name[nname][strlen(name[nname])-2] = '\0'; 
+0

,我需要2-d阵列在结果 – Wilson 2012-07-07 12:09:06

+0

印刷收集串新的代码编译好我的机器上 – 2012-07-07 12:27:14

+0

感谢您的宝贵时间,我都试过了,但它仍然是在另一条线路 – Wilson 2012-07-07 12:39:06

2

我用GCC 4.4.1编译它 - MinGW和它工作正常。 它发起了一个警告。这是结果:

warning: return type of 'main' is not 'int'| 
||=== Build finished: 0 errors, 1 warnings ===| 

现在它可以作为你的期望。

#include <stdio.h> 
#include<stdlib.h> 
#include<ctype.h> 
#include <string.h> // strlen() 

void main() { 
    char name[100][52],selection[2]="Y"; 
    int x,nname=1; 
    float sales; 

    do { 
     printf("Enter name: "); 
     fflush(stdin); 
     fgets(name[nname],51,stdin); // i need put a wrapper in here 
     for (x=0; x<strlen(name[nname]); x++){ // this will discarge the \n 
     if (name[nname][x] == '\n') 
      name[nname][x] = '\0'; 
     } 
     printf("Enter sales: "); 
     scanf("%f",&sales); 
     if (sales<1000) 
      printf("%s\tgood\n",name[nname++]); 
     else 
      printf("%s\tvry good\n",name[nname++]); 
     printf("Enter another name?(Y/N)"); 
     fflush(stdin); 
     fgets(selection,2,stdin); 
     *selection=toupper(*selection); 
    } while(nname<=100 && *selection=='Y'); 
    for(x=1; x<nname; x++) 
     printf("%s ",name[x]); // want print the result without(newline) /n 

    printf("\nEND\n"); // inserted \n before END 
    system("pause"); 
} 
+0

编码是工作,但结果我需要它是所有的名字在一行例'name1 name2 name3' – Wilson 2012-07-07 12:34:51

+0

感谢您的帮助! :) – Wilson 2012-07-07 14:44:12