如何让我的 C 程序识别“\n”字符并忽略它们
How to make my c-program recognize "\n" characters and ignore them
我正在编写一个程序,用于检查特定输入字符串是否仅包含特定类型的字符(ASCII 字符)。我有一串属于 ASCII 标准的字符,对于输入字符串中的每个字符,我检查(逐个字符)它是否存在于 ASCII 字符串中。如果这个字符确实存在,我会将它们移动到一个新的字符串,一个输出字符串。如果它们不存在,我会通知用户并退出程序。
但是,我制作的输入字符串既可以从命令行创建,也可以从文本文件创建。我的文本文件似乎总是包含几个换行符,并且它们总是以换行符(“\n”字符)结尾,这总是使我的程序在字符串末尾或中间报告错误。
如何重新排列以下程序的代码以使其识别“\n”字符?下面是代码的简化,没有显示我如何定义输入字符串或带有 ASCII 字符的字符串。
char inputstring[];
char outputstring[];
char asciicharacters[];
* Here I read a text-file to the inputstring, and the ASCII-characters to the asciicharacters-string *
int k,i=0;
for(i=0;i<strlen(inputstring);i++)
{
for(k=0;k<strlen(asciicharacters);k++)
{
if(inputstring[i] == asciicharacters[k])
{
outputstring[i] = inputstring[i];
break;
}
else if(k == strlen(asciicharacters)-1)
{
printf("The character: %c, is not ASCII-standard",input[i]);
exit(1);
}
}
}
当我到达“\n”字符时,如何创建另一个条件使程序跳过(并接受为 ASCII 标准)?
您可以在最后的 else if
之前添加此 else if
。
else if( inputstring[i] == '\n' )
{
break;
}
我正在编写一个程序,用于检查特定输入字符串是否仅包含特定类型的字符(ASCII 字符)。我有一串属于 ASCII 标准的字符,对于输入字符串中的每个字符,我检查(逐个字符)它是否存在于 ASCII 字符串中。如果这个字符确实存在,我会将它们移动到一个新的字符串,一个输出字符串。如果它们不存在,我会通知用户并退出程序。
但是,我制作的输入字符串既可以从命令行创建,也可以从文本文件创建。我的文本文件似乎总是包含几个换行符,并且它们总是以换行符(“\n”字符)结尾,这总是使我的程序在字符串末尾或中间报告错误。
如何重新排列以下程序的代码以使其识别“\n”字符?下面是代码的简化,没有显示我如何定义输入字符串或带有 ASCII 字符的字符串。
char inputstring[];
char outputstring[];
char asciicharacters[];
* Here I read a text-file to the inputstring, and the ASCII-characters to the asciicharacters-string *
int k,i=0;
for(i=0;i<strlen(inputstring);i++)
{
for(k=0;k<strlen(asciicharacters);k++)
{
if(inputstring[i] == asciicharacters[k])
{
outputstring[i] = inputstring[i];
break;
}
else if(k == strlen(asciicharacters)-1)
{
printf("The character: %c, is not ASCII-standard",input[i]);
exit(1);
}
}
}
当我到达“\n”字符时,如何创建另一个条件使程序跳过(并接受为 ASCII 标准)?
您可以在最后的 else if
之前添加此 else if
。
else if( inputstring[i] == '\n' )
{
break;
}