使用sscanf从c++文件中读取空格分隔符

using sscanf for space delimiter reading from file C++

本文关键字:读取 空格 分隔符 文件 sscanf c++ 使用      更新时间:2023-10-16
#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]