我有一个包含多行字符串,整数,整数值的文件。
Delhi,12,13
Mumbai,100 , 101
Kolkata,11, 12
这些值之间用逗号分隔,但是它们之间可能会有空白。我当前的代码是这样的:
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
int main()
{
FILE *f = fopen("input.txt","r");
int lines = 0;
char c = getc(f);
while(c != EOF)
{
if(c == '\n')
{
lines++;
}
c = getc(f);
}
lines++;
string arr[lines];
int t1[lines];
int t2[lines];
char s1[100],s2[100],s3[100];
int x,y;
fclose(f);
f = fopen("input.txt","r");
while (fscanf(f,"%99[^,],%99[^,],%99[^,]", s1, s1, s2)==3)
{
cout << s1 << s2 << s3 << endl;
}
}
首先,这似乎不太正确地读取了值并显示在屏幕上。我如何在这里读取字符串和整数值(可能会有杂散的空格)并将它们存储到一个数组中(准确地说是三个数组)?
尝试这样做:
fscanf(f,"%[^, ]%*[ ,]%d%*[ ,]%d ", s1, &x, &y);
%[^, ]
=>搜索一切除,
和<space>
,并将其存储在S1中
%*[ ,]
=>搜索,
并且<space>
不将其存储在任何地方(*
确保确保)
%d
=>存储号码
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句