Monday, January 9, 2012

C++的getline與以strtok作字串分割

以下程式可以以getline輸入加法的字串,例如"1.1 + 2 + 3.5 + 4",輸出為這幾個數的和。方法就是以strtok分割字串,然後以atof轉成數值,然後把值將加後,最後得到結果
 
#include "iostream"
#include "stdlib.h"
#include "string.h"
#include "stdio.h"

using namespace std;

int main()
{
 char str[256];

 cout << "請輸入加法運算字串,例如1.1 + 2 + 3.5 + 4 : \n";
 cin.getline(str, 100);

 char *delim = "+";
 char * pch;
 int i = 0, j;
 double answer = 0;
 double values[4];

 pch = strtok(str, delim);

 while (pch != NULL)
 {
  values[i] = atof(pch);
  cout << "values[i] = " << values[i] << endl;
  pch = strtok(NULL, delim);
  i++;
 }

 for ( j = 0 ; j < i ; j ++)
  answer = answer + values[j];

 cout << "這" << i << "個數的和為" << answer << endl;

 system("pause");
 return 0;
}

No comments:

Post a Comment