2012-07-07 151 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