fscanf_s

codePorter-faceCV 2019-07-17 04:14:36
fscanf_s如何读取两个字符,我这样写运行出错?
...全文
998 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
轻箬笠 2019-07-19
  • 打赏
  • 举报
回复
深入理解C++11:C++11新特性解析与应用
codePorter-faceCV 2019-07-19
  • 打赏
  • 举报
回复
引用 4 楼 轻箬笠的回复:
#include <stdio.h>
#include <string.h>
int main()
{
	FILE *file = NULL;
	char a[10];
	char b[10];
	fopen_s(&file, "11.txt", "w+");
	fprintf_s(file, "%s %s", "aaaaa", "bbb");
	fseek(file, 0, SEEK_SET);
	fscanf(file, "%s %s", a, b);
	fclose(file);
	return 0;
}
fscanf从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。 用fscanf也可以实现楼主的类似要求。只是逗号需要变成空格
谢了,还有一个问题,请问有没有学c++11语法的书,好多这样的语法我都找不到
轻箬笠 2019-07-18
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <string.h>
int main()
{
	FILE *file = NULL;
	char a[10];
	char b[10];
	fopen_s(&file, "11.txt", "w+");
	fprintf_s(file, "%s %s", "aaaaa", "bbb");
	fseek(file, 0, SEEK_SET);
	fscanf(file, "%s %s", a, b);
	fclose(file);
	return 0;
}
fscanf从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。 用fscanf也可以实现楼主的类似要求。只是逗号需要变成空格
轻箬笠 2019-07-18
  • 打赏
  • 举报
回复
// crt_fscanf_s.c
// This program writes formatted
// data to a file. It then uses fscanf to
// read the various data back from the file.

#include <stdio.h>
#include <stdlib.h>

FILE *stream;

int main( void )
{
   long l;
   float fp;
   char s[81];
   char c;

   errno_t err = fopen_s( &stream, "fscanf.out", "w+" );
   if( err )
      printf_s( "The file fscanf.out was not opened\n" );
   else
   {
      fprintf_s( stream, "%s %ld %f%c", "a-string",
               65000, 3.14159, 'x' );
      // Set pointer to beginning of file:
      fseek( stream, 0L, SEEK_SET );

      // Read data back from file:
      fscanf_s( stream, "%s", s, _countof(s) );
      fscanf_s( stream, "%ld", &l );

      fscanf_s( stream, "%f", &fp );
      fscanf_s( stream, "%c", &c, 1 );

      // Output data read:
      printf( "%s\n", s );
      printf( "%ld\n", l );
      printf( "%f\n", fp );
      printf( "%c\n", c );

      fclose( stream );
   }
}
受教育了,把fscanf和fscanf_s混为一谈了。上面是fscanf_s的各种用法,读取字符串时,需要指定长度。
codePorter-faceCV 2019-07-18
  • 打赏
  • 举报
回复
引用 1 楼 轻箬笠的回复:
首先文件打开用fopen_s,参数应该是w+
第二,你想读取刚写入的字符,需要用fseek,把文件读取位置设置好。
为什么我可以读一个字符串,而读两个就出错了。
轻箬笠 2019-07-17
  • 打赏
  • 举报
回复
首先文件打开用fopen_s,参数应该是w+
第二,你想读取刚写入的字符,需要用fseek,把文件读取位置设置好。

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧