史萊姆論壇

史萊姆論壇 (http://forum.slime.com.tw/)
-   程式語言討論區 (http://forum.slime.com.tw/f76.html)
-   -   關於C++資料讀取的問題 (http://forum.slime.com.tw/thread228433.html)

oking 2008-04-19 04:28 PM

關於C++資料讀取的問題
 
有一個作業需要做除法運算,分子分母要分別讀出,

如:

狀況1.當我輸入 -8/3 時可讀出分子為-8,分母為3。

狀況2.當我輸入 2 時可自行讀到分子為2,分母為1。

狀況3.沒有輸入即當做0。



我寫的code問題在於:



int 分子, 分母;

char temp;

cin >> 分子 >> temp >> 分母;



但是只有狀況1能讀到資料,狀況2和3就不行了。



請問我該如何修改。

mini 2008-04-19 05:37 PM

宣告時給他預設值

int 分子=0, 分母=1;

rank 2008-04-28 02:06 AM

語法:

#include<iostream>
#include<cstdio>
using namespace std;
int main (void)
{
  char buffer[1024];
  int a,b;
  char c;

  while(gets(buffer)){
       
          if(sscanf(buffer,"%d%c%d",&a,&c,&b)==3){
                  printf("%d %d\n",a,b);
                  continue;
          }

          if(sscanf(buffer,"%d",&a)==1){
                  b=1;
                  printf("%d %d\n",a,b);
                  continue;
          }else{
                  a=0;
                  b=1;
                  printf("%d %d\n",a,b);
                  continue;
          }
 
 
 
  } 
  system("pause");
  return 0;
}



所有時間均為台北時間。現在的時間是 04:01 PM

Powered by vBulletin® 版本 3.6.8
版權所有 ©2000 - 2025, Jelsoft Enterprises Ltd.

『服務條款』

* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *


SEO by vBSEO 3.6.1