读取多个字符串并在C中使用多个大小写浮动



这里的主要问题是我有两个字符串和一个浮点值要读取。字符串的大小是10个字节,但无论是什么输入,我都应该能够读取并将其存储在字符串中。例如:如果我的输入是Hello world!,那么字符串应该是string = "Hello wor"

如果我的输入是Hello,那么字符串应该是string = "Hello"

现在你可能会认为这是显而易见的,只需使用fgets,对吗?但在读取第二个字符串时,这会带来缓冲区问题。问题是,我确实找到了一个修复方法,但这涉及到使用fflush函数,但它似乎在少数编译器中不起作用。

我搜索了一个替代方案,找到了while ( getchar() != 'n'),但它实际上并不像fflush那样工作。

所以我想问的是,无论输入的长度如何,都有更好的方法来读取字符串吗?这就是我想到的:

#include <stdio.h> 
#include <string.h>
int main(int argc, char** argv) {
char nom[10] , prenom[10];
double salaire;
fgets( nom , sizeof( nom ) , stdin );
nom[ strcspn( nom , "n") ] = 0;
fflush(stdin);
fgets( prenom , sizeof( prenom ) ,stdin );
prenom[ strcspn( prenom , "n") ] = 0;
fflush(stdin);
scanf("%lf",&salaire);
printf("%sn",nom);
printf("%sn",prenom);
printf("%lfn",salaire);
return 0;
}

在这种情况下,fgets在读取输入时包含'n'实际上很有用。如果n在字符串的末尾,则意味着fgets能够读取整行直到末尾。如果是其他字符,则意味着fgets在到达行的末尾之前停止,并且整行未被读取。只有在整行未被读取的情况下,我们才能使用getchar()循环来清除stdin

#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[10], str2[10];
fgets(str1, sizeof str1, stdin);
if (str1[strlen(str1) - 1] != 'n')
for (int c; (c = getchar()) != 'n' && c != EOF;);
fgets(str2, sizeof str2, stdin);
if (str1[strlen(str1) - 1] != 'n')
for (int c; (c = getchar()) != 'n' && c != EOF;);

// Now it's safe to remove the n
str1[strcspn(str1, "n")] = '';
str2[strcspn(str2, "n")] = '';
printf("%sn%sn", str1, str2);
}

您甚至可以在fgets周围制作一个简单的包装器,每当您阅读一行时都可以这样做:

char *readln_and_clear(char *buf, size_t bufsz, FILE *stream)
{
if (fgets(buf, bufsz, stream) == NULL)
return NULL;
if (buf[strlen(buf) - 1] != 'n')
for (int c; (c = fgetc(stream)) != 'n' && c != EOF;);
// If you want
buf[strcspn(buf, "n")] = '';

return buf;
}

如果你希望每个字符串都在自己的行上,你可以使用这个解决方案:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ReadLine(char result[], int resultLen)
{
int ch, i;
assert(resultLen > 0);
i = 0;
ch = getchar();
while ((ch != 'n') && (ch != EOF)) {
if (i < resultLen - 1) {
result[i] = ch;
i++;
}
ch = getchar();
}
result[i] = '';
}

int main(int argc, char *argv[])
{
char nom[10], prenom[10];
double salaire;
int n;
ReadLine(nom, sizeof(nom));
ReadLine(prenom, sizeof(prenom));
n = scanf("%lf", &salaire);
if (n == 1) {
printf("%sn", nom);
printf("%sn", prenom);
printf("%fn", salaire);
} else {
fprintf(stderr, "Reading salaire failed, number expectedn");
exit(EXIT_FAILURE);
}
return 0;
}

最新更新