使用sscanf从c++文件中读取空格分隔符
using sscanf for space delimiter reading from file C++
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[])
{
ifstream ifile;
char fName[30][30];
long int uTime[30][10];
ifile.open("sync.log");
char ch;
string str = "";
if(ifile.fail())
{
cout<<"Invalid File Name!";
system("pause");
exit(1);
}
int i = 0;
while(!ifile.eof())
{
getline(ifile, str);
cout<<str<<endl;
sscanf(str.c_str(),"%ld %[^n]",&uTime[i],fName[i]);
i++;
str = "";
}
ifile.close();
system("pause");
cout<<"Output:"<<endl;
for(i = 0 ; i < 2 ; i ++)
{
cout<<uTime[i]<<" ";
cout<<fName[i];
cout<<endl;
}
getch();
return 0;
}
文件: sync.log
格式:
1399865017 Test1.txt
1399865017 Test1.txt
所以这里是我的完整代码,我有同步日志文件在根目录,其中vc++保存的项目…
read from File
后必须像这样存储在数组中uTime[0] = 1399865017;
fName[0] = "Test1.txt";
fName[1] = "Test1.txt";
使用上面的代码,我得到
uTime[0] = 0012F6B0 and fName[0] = "Test1.txt"
and i want this
uTime[0] = 1399865017;
fName[0] = "Test1.txt";
我想你的意思是:
long int uTime[30];
不是long int uTime[30][10];
这样,将数据读入uTime
的那行和将uTime
写入cout
的那行就有意义了。
如果你有:
long int uTime[30][10];
:
cout << uTime[i] << …
您正在打印一个指向10个long
的数组的指针。该指针是十六进制格式的;这就是为什么你得到十六进制输出。
您需要修复sscanf()
调用-您在那里得到了&uTime[i]
的假参数-以及输出。由于不清楚为什么uTime
是一个2D数组,所以不容易告诉您如何修复它,但最简单的解决方案是从数组定义中删除[10]
。
相关文章:
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 如何在 QT 中从.txt文件中读取空格
- 我无法读取空格并使用 devc++ 输入 c++
- 读取空格会使解析器崩溃.为什么?
- 未读取空格
- 从文件中读取空格
- 读取空格将数字从文本文件分隔到整数数组 (C++)
- 字符串没有变蓝,只读取空格
- std::stringstream 不读取空格
- 从文件中读取空格分隔的数字
- 使用 getline() 读取空格不起作用
- 有没有一种不使用std::getline从文件中读取空格的方法?
- 从文件中读取空格分隔的数字,直到换行符
- 不会使用 ifstream 读取空格
- 从 ifstream 读取不会读取空格
- 使用sscanf从c++文件中读取空格分隔符
- 用空格数据读取空格分隔的数据