我如何摆脱这条新线?

时间:2013-10-04 15:19:26

标签: c newline

我创建了一个程序,要求用户输入他们的名字,然后以多种方式操作它。它操纵它的最后一种方法是向后打印用户名。例如,如果用户输入John Doe,程序将打印Doe John。我现在唯一的问题就是阻止我的程序在姓氏和名字之间添加一条不必要的新行。

实施例: 我希望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);


 }

3 个答案:

答案 0 :(得分: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结尾的无线buf,并且输入缓冲区中没有任何内容可以破坏您的下一个fgets来电。

答案 1 :(得分: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  

编辑

您的代码

#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

答案 2 :(得分: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 }

BTW:OP在fgets(name,(sizeof(name)-1),stdin)中不需要-1。