Я создал программу, которая просит пользователя ввести свое имя, а затем манипулировать им несколькими способами. Последний способ, которым он управляет, - это напечатать имя пользователя назад. Например, если пользователь ввел Джона Доу, программа напечатала бы Доу Джона. Единственная проблема, с которой я столкнулась в данный момент, - это остановить мою программу от ненужной новой строки между последним и первым именем.Как мне избавиться от этой новой строки?
Пример: Я хочу 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);
}
Примечание: fgets() должен принимать 'sizeof (name)', без '-1'. – Medinoc