C++:使用 fgets() 读取字符输入时出错

C++: error in reading character input using fgets()

本文关键字:读取 字符输入 出错 使用 fgets C++      更新时间:2023-10-16

我已经尝试了一个简单的代码来使用fgets((,因为gets((不再使用,并且不知道从键盘读取字符输入更好的方法。我的代码:

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
char a;
fgets(a, 100, stdin);
cout<<a;
return 0;
}

我收到此错误:

cpp:13:20: error: invalid conversion from 'char' to 'char*' [-fpermissive]
 fgets(a, 100, stdin);
                    ^
In file included from /usr/include/c++/7.2.0/cstdio:42:0,
                 from /usr/include/c++/7.2.0/ext/string_conversions.h:43,
                 from /usr/include/c++/7.2.0/bits/basic_string.h:6159,
                 from /usr/include/c++/7.2.0/string:52,
                 from /usr/include/c++/7.2.0/bits/locale_classes.h:40,
                 from /usr/include/c++/7.2.0/bits/ios_base.h:41,
                 from /usr/include/c++/7.2.0/ios:42,
                 from /usr/include/c++/7.2.0/ostream:38,
                 from /usr/include/c++/7.2.0/iostream:39,
                 from jdoodle.cpp:1:
/usr/include/stdio.h:564:14: note:   initializing argument 1 of 'char* fgets(char*, int, FILE*)'
 extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
              ^~~~~

然后,我试过了

#include<iostream>    
#include<cstdio>
using namespace std;

int main()
{
char *a;
fgets(a, 100, stdin);
cout<<a;
return 0;
}

但又出现了一个错误。

如果有人展示除使用 fgets(( 或解决上述问题之外的更好方法,将不胜感激。

你用错char *fgets(char *str, int n, FILE *stream)。它旨在从文件中读取多个字符,实际上最多 n-1 个字符,最后一个字符将是 null 终止符。

您可以使用int getc(FILE *stream)来读取单个字符,如下所示:

int a;
if((a = getc(stdin)) != EOF) {
  // use a 
  char c = a; // convert to char explicitly
}

当你使用c ++时,更好的方法是使用cin stream:

char a;
// formatted read(skips whitespace)
cin >> a;
// non-formated read
a = cin.get();

并且不要忘记在每次读取后检查操作是否成功:

if(cin) {
  // success -> stream is ok
} else {
  // handle read error
}

如果要读取多个字符:

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
  char a[100]; // allocate static buffer
  fgets(a, 100, stdin); // read in the buffer
  cout << a;
  return 0;
}

此外,c ++的方式是:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string s; // string that automatically manages memory
  cin >> s; // reads non-whitespace sequence of characters
  cout << s;
  return 0;
}

另一种选择是读取一行字符,最多读取n包括空格。

#include <iostream>
#include <string>
using namespace std;
int main () {
  string s;
  getline(cin, s);
  cout << s;
  return 0;
}

变量 a 是未分配的字符指针。将"a"声明为固定长度数组: 字符 A[100];或使用 malloc 将内存分配给"a":

a=(char*)malloc( 100*sizeof(char) );

你需要取消引用一个

char a[100];
fgets(&a, 100, stdin);
cout << a << endl;
return 0;

fgets 的定义在第一个参数中有指针。当您尝试使用

char a;

自动为 1 个字符分配空间。

当您使用

char *a;

您必须使用 Malloc 分配您的空间