2016-06-16 111 views
-3

只想從文件中讀取數字&將它們存儲在數組中。我不知道文件處理。請幫助我。heelp我從C++文件中讀取nos?

#include iostream conio.h 
#stdio.h string fstream; 
using namespace std; 
int main() 
{ 

ifstream myfile("ashishdata.txt");//file open 

char c; 
char arr[100]; 
int i=0; 
// read data from file 

while (myfile.get(c)) 
{ 
    if(isdigit(c) || c=='.') 
    { 
    arr[i] = c; 
    i++; 
    } 
} 
arr[i]='\0';//mark end of array 
myfile.close();//file closed 
int k; 
k=strlen(arr); 
//parsing string 
int newarr[100]; 
int m=0; 
string(s); 
for(i=0;i<=k;i++) 
{ 
    s.erase(); 
    while(arr[i] != '.') 
    { 
     s+=arr[i]; 
     i++; 
    } 
    newarr[m]=atoi(s.c_str()); 
    m++; 
} 

newarr[m]='\0'; 
//printing newarray 
i=0; 
while(newarr[i]!='\0') 
{ 
    cout<<newarr[i]<<'\t'; 
    i++; 
} 
cout<<endl; 

getch(); 
return(0); 
} 
+1

檢查這個問題/答案:http://stackoverflow.com/questions/14516915/read-數字數據從一個文本文件在C – AnalyticaL

+0

也學習[如何提出一個很好的問題](http://stackoverflow.com/help/how-to-ask)第一 –

回答

0

試試這個:

filename.txt: 4545.454 SDS 65.65.6.65656

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstring> 
using namespace std; 

int main() { 
    char c; 
    char arr[100]; 
    size_t i = 0; 
    // read data from file 
    ifstream myfile; 
    myfile.open("filename.txt", ios::in); 
    while (!myfile.eof()) { 
    myfile >> c; 
    if (isdigit(c) || c == '.') { 
     arr[i] = c; 
     i++; 
    } 
    } 
    arr[i] = '\0'; // mark end of array 
    myfile.close(); // file closed 
    size_t k = strlen(arr); 
    // parsing string 
    int newarr[100]; 
    int m = 0; 
    string s; 
    for (i = 0; i <= k; i++) { 
    s.erase(); 
    while (arr[i] != '.') { 
     s += arr[i++]; 
    } 
    newarr[m++] = atoi(s.c_str()); 
    } 

    newarr[m] = '\0'; 
    // printing newarray 
    i = 0; 
    while (newarr[i] != '\0') { 
    cout << newarr[i++] << '\t'; 
    } 
    return 0; 
}