如何从该字符串中提取碎片?将字符串切成块
我有一个包含文件:
0065445 APPLE$456
089464 MANGO$489
0GUAVA$744
我想要做的就是通过输入行的文件行,然后切串入一些碎片。
- 0065455准备到结构
a[0].num
- 苹果将在结构
a[0].name
- 456去将结构
a[0].dollar
去
同样地,对于其他线路。
一切工作正常,但它没有成功地将美元部分放入其变量中。
下面的代码:
#include<cstdlib>
#include<iostream>
using namespace std ;
int main(){
FILE *fp;
fp = fopen("input.txt","r");
char str[80] ;
struct abc{
int num;
char name[20];
int dollar;
};
int i = 0;
while(fgets(str,79,fp)!=NULL){
struct abc a[i] ;
sscanf(str,"%d %[^$]s$%d\n",&a[i].num,a[i].name,&a[i].dollar);
cout <<i+1 <<") Number : "<<a[i].num<<" Name : "<< a[i].name <<" Dollar : "<< a[i].dollar << endl ;
i++;
}
return 0 ;
}
/* These didn't work too.
sscanf(str,"%d %[^$]s %d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %[^$]s%d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %s$%d\n",&a[i].num,a[i].name,&a[i].dollar);
*/
有1点更多的问题:字符串的第一部分是从0开始int,但零没有在INT被接受。怎么做?
这是工作,我现在想,但还是parasing串入一个int后,我没有得到的零:
#include<cstdlib>
#include<iostream>
#include<cstring>
using namespace std ;
int main(){
FILE *fp;
fp = fopen("input.txt","r");
char str[80] ;
char temp[80] ;
struct abc{
int num;
char name[20];
int dollar;
};
int i = 0;
int j = 0 ;
while(fgets(str,79,fp)!=NULL){
i = 0;
j = 0 ;
struct abc a[i] ;
char* ptr = 0; // this is used as a helper variable to strtok
ptr = strtok(str, " $\n"); // we specify the delimiters here
while (ptr != NULL)
{
if (j == 0){
strcpy(temp, ptr);
a[i].num = atoi(temp);
}
if (j == 1)
strcpy(a[i].name, ptr);
if (j == 2){
strcpy(temp, ptr);
a[i].dollar = atoi(temp);
}
ptr = strtok(NULL, " $\n");
j++;
}
cout <<i+1 <<") Number : "<<a[i].num<<" Name : "<< a[i].name <<" Dollar : "<< a[i].dollar << endl ;
i++;
}
return 0 ;
}
/* These didn't work either.
sscanf(str,"%d %[^$]s %d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %[^$]s%d\n",&a[i].num,a[i].name,&a[i].dollar);
sscanf(str,"%d %s$%d\n",&a[i].num,a[i].name,&a[i].dollar);
*/
你的意思是'0065455会在struct a [0] .num'中出现吗? (而不是'a [0] .int') –
sscanf在“[^ $]”命中时“停止扫描”。您需要第二个sscanf,从您离开的位置开始(读取的字符数由sscanf返回),然后在$符号后读取该值。 – Floris
他想提取字符串在三块,逻辑是,他应该找到第一个'space',第二'$''从APPLE 0065445 $ 456',他将得到'0065445','APPLE'和'456' – vikas