2013-10-04 4 views
2

Я создал программу, которая просит пользователя ввести свое имя, а затем манипулировать им несколькими способами. Последний способ, которым он управляет, - это напечатать имя пользователя назад. Например, если пользователь ввел Джона Доу, программа напечатала бы Доу Джона. Единственная проблема, с которой я столкнулась в данный момент, - это остановить мою программу от ненужной новой строки между последним и первым именем.Как мне избавиться от этой новой строки?

Пример: Я хочу Doe John на одной линии, но я получаю

Doe 
John 

Для моего назначения мне нужно, чтобы избавиться от этой дополнительной линии. Как мне это сделать?

#include <stdio.h> 
#include <string.h> 

void removeNewLine (char * userName, int charLenght) 
{ 
    int i=0; 

    do { 
     if (userName [i]=='\n') 
     { 
      userName [i]='\0'; 
     } 
    i++; 
    } while (i<charLenght); 

} 

// This is going to tell me exactly how many real character are in my array 
int myCounter (char * userName, int size) 
{ 
    int counter=0; 
     do 
     { 
      if(userName [counter]=='\0') 
      { 
       return counter; //I always thought that you needed to put your return at the end of the function, this is good to know that you don't need too 
      } 
      counter++; 
     }while (counter<size); 
    return -1; 
} 


int main() 
{ 
printf("Enter your first and last name\n"); 

char name [250]={'\0'}; 
char * space; 
char *first=NULL, *last = NULL, *firstspace; 
char *userName; 
int numOfChars=0; 
//Prevents the potential problem of an overflow = (sizeof(name)-1) 
fgets(name,(sizeof(name)-1),stdin); 

//This is what is actually doing the dirty work of removing the extra chars 

removeNewLine(userName, numOfChars); 

//This is going to count the number of characters that were input by the user 

numOfChars = strlen(name)-1; 

printf("You Entered: %s  \n", name); 
printf("There are %zu characters in your name including the space. \n", strlen(name)); 

char end; 
int i; 
end = strlen(name) -1; 
printf("Your name backwards is"); 
for (i = end; i >= 0; --i) 
{ 
printf("%c", name [i]); 
} 

printf("\nLooking for the space in your name \n", name); 
firstspace=space=strchr(name, ' '); 
*firstspace='\0'; 
while (space!=NULL) 
{ 
    printf("The space was found at character %d\n", space-name+1); 
    last = space+1; 
    space=strchr(space+1, ' '); 
} 

printf("%s%s", last, name); 
*firstspace=' '; 

//This is just to tell the user how many "real" characters were in there name 
printf("\n There are %d actual characters in your name including the space", numOfChars); 


} 
+0

Примечание: fgets() должен принимать 'sizeof (name)', без '-1'. – Medinoc

ответ

0

мало изменений и Поменяйте их ниже двух линий

removeNewLine(userName, numOfChars); 

    //This is going to count the number of characters that were input by the user 

    numOfChars = strlen(name)-1; 

Как это

numOfChars = strlen(name); // first find the length of input. 
removeNewLine(name, numOfChars); // And now remove newline at the end of input 

EDIT

Ваш код

#include <stdio.h> 
#include <string.h> 

void removeNewLine (char * userName, int charLenght) 
{ 
    int i=0; 

    do { 
     if (userName [i]=='\n') 
     { 
      userName [i]='\0'; 
     } 
    i++; 
    } while (i<charLenght); 

} 


int main() 
{ 
printf("Enter your first and last name\n"); 

char name [250]={'\0'}; 
char * space; 
char *first=NULL, *last = NULL, *firstspace; 
int numOfChars=0; 
//Prevents the potential problem of an overflow = (sizeof(name)-1) 
fgets(name,(sizeof(name)-1),stdin); 

//This is what is actually doing the dirty work of removing the extra chars 

numOfChars = strlen(name); // first find the length of input. 
removeNewLine(name, numOfChars); // And now remove newline at the end of input 
printf("You Entered: %s  \n", name); 
printf("There are %zu characters in your name including the space. \n", strlen(name)); 

char end; 
int i; 
end = strlen(name) -1; 
printf("Your name backwards is"); 
for (i = end; i >= 0; --i) 
{ 
printf("%c", name [i]); 
} 

printf("\nLooking for the space in your name \n", name); 
firstspace=space=strchr(name, ' '); 
*firstspace='\0'; 
while (space!=NULL) 
{ 
    printf("The space was found at character %ld\n", space-name+1); 
    last = space+1; 
    space=strchr(space+1, ' '); 
} 

printf("%s %s", last, name); 
*firstspace=' '; 

//This is just to tell the user how many "real" characters were in there name 
printf("\n There are %d actual characters in your name including the space", numOfChars); 


} 

Выход

Enter your first and last name 
John Doe 
You Entered: John Doe 
There are 8 characters in your name including the space. 
Your name backwards iseoD nhoJ 
Looking for the space in your name 
The space was found at character 5 
Doe John 
There are 9 actual characters in your name including the space 
+0

Я все еще получаю новую строку – user2172993

+0

Добавлен модифицированный код и вывод. видеть, что вы хотите? – Gangadhar

+1

Ничего, это сработало, я не удалял -1. Спасибо, тонну. – user2172993

0

Лучший способ заключается в использовании fgets() с парой вспомогательных функций:

/*Removes remaining characters from keyboard input buffer until next newline*/ 

/*Returns 0 if OK, a negative value if EOF.*/ 
int fpurge(FILE *f) 
{ 
    int c; 
    while((c=fgetc(f))!=EOF && c!='\n') 
    { } 
    return (c==EOF ? -1 : 0); 
} 

/*Find and remove newline from string*/ 

/* Returns a nonzero value if found, zero if not. */ 
int truncate_newline(char *str) 
{ 
    int bRet=0; 
    if(str!=NULL) 
    { 
     char *pNewline = strchr(str, '\n'); 
     if(pNewLine!=NULL) 
     { 
      bRet = 1; 
      *pNewLine = '\0'; 
     } 
    } 
    return bRet; 
} 

/*Remove newline from string or excess characters from input buffer, 
where appropriate.*/ 

/* Returns 0 if buffer is full, a positive value if line is complete, 
    a negative value if EOF (implies buffer full). */ 
int fclean(char *str, FILE *f) 
{ 
    int ret = 1; 
    if(!truncate_newline(str)) 
     ret = fpurge(f); 
    return ret; 
} 

Он используется так:

char buf[42]; 
fgets(buf, sizeof buf, stdin); 
fclean(buf); 

Теперь у вас есть NULL-terminated, newlineless buf, и ничто во входном буфере не повредит ваш следующий fgets звонок.

+0

Я по-прежнему получаю такую ​​же проблему даже после копирования этой программы в свою программу. Есть что-то, что мне нужно удалить первым? – user2172993

+0

Обычно вам просто нужно заменить вызов 'removeNewLine' вызовом' fclean' ... – Medinoc

0

Как предложить "после того, как принято решение".

void *removeNewLineAfter_fgets(char *s) { 
    if (s) { 
    size_t l = strlen(s); 
    if ((l > 0) && (s[l-1] == '\n')) { 
     s[l-1] = '\0'; 
    } 
    } 
    return s; 
} 

// Usage: 
if (removeNewLineAfter_fgets(fgets(name,sizeof(name),stdin)) == NULL) { handle EOF } 

КСТАТИ: OP не нужно -1 в fgets(name,(sizeof(name)-1),stdin).

Смежные вопросы