1. 程式人生 > >C++ 讀取字符串中的數字

C++ 讀取字符串中的數字

一個 error strings ror read std ostream code lin

今天真是試了各種方法,笨方法聰明方法都有了

方法1:一個字符一個字符的讀取

方法2:借助strtok實現split 適用於char

方法3:借助istringstream實現split 適用於string

// 方法1:一個字符一個字符讀取
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
    ifstream fin("data.txt");
    if(! fin.is_open())
    {
        cout
<<"Error opening file"<<endl;exit(1); } char str; int num[10001]; int i=0;num[i] = 0; bool IsNegative = false; while(!fin.eof()){ fin.read(&str,1); if(str == ){ if(IsNegative) num[i] = -num[i]; printf("%d ",num[i]); i
+= 1;num[i] = 0; IsNegative = false; } else if(str == \0 || str == \n){ if(IsNegative) num[i] = -num[i]; printf("%d ",num[i]); i += 1;num[i] = 0; break; } else if(str == -){ IsNegative = true; }
else{ num[i] = num[i]*10 + (str-0); } } return 0; }
//方法2:借助strtok實現split 適用於char
#include <iostream>
#include <string>
#include <fstream>
#include <string.h>
#include <stdio.h>
using namespace std;
int ReadNum(char *str){
    int i = 0;
    int num = 0;
    if(str[0] == -){
        i += 1;
    }
    while(str[i]){
        num = (str[i]-0) + num*10;
        i += 1; 
    }
    if(str[0] == -){
        num = -num;
    }
    return num;
}

int main()
{
    ifstream fin("data.txt");
    if(! fin.is_open())
    {
        cout<<"Error opening file"<<endl;exit(1);
    }
    char s[10001];
    int num[101];int i = 0;
    fin.getline(s,10001);
    const char *d = " ";
    char *p;
    p = strtok(s,d);
    while(p)
    {
            num[i] = ReadNum(p);
            printf("%d ",num[i]);
            i+=1;
            p=strtok(NULL,d);
    }
    return 0;
}
//方法3:借助istringstream實現split 適用於string 
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std ;
int ReadNum(string str){
    int i = 0;
    int num = 0;
    if(str[0] == -){
        i += 1;
    }
    while(str[i]){
        num = (str[i]-0) + num*10;
        i += 1; 
    }
    if(str[0] == -){
        num = -num;
    }
    return num;
}
int main(){
    ifstream fin("data.txt");
    if(! fin.is_open())
    {
        cout<<"Error opening file"<<endl;exit(1);
    }
    string str;
    getline(fin, str);
    string sTmp;
    istringstream istr(str);
    int num[100000];int i = 0;
    while(!istr.eof()){
        istr >> sTmp; //get a word
        num[i] = ReadNum(sTmp);
        printf("%d ", num[i]);
        i += 1;
    }
    return 0;
} 

C++ 讀取字符串中的數字