如何從該字符串中提取碎片?將字符串切成塊
我有一個包含文件:
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