2013-05-09 87 views
0

我在制作一个程序,并且有一个需要读取的.txt文件,并从中获取命令。文本文档看起来像:从C++的多行txt文档中读取一个数字

U 
R 
F 10 
D 
F 13 
Q 

我需要从中得到数字。即时读取文件的方式来自名为instreamifstream对象。目前我使用

while(instream.get(charVariable)){ 
    switch(charVariable){ 
    case 'F': //do the forward command 
     break; 
    ... 
    } 
} 

正向命令需要采取线,这样做,它需要读取F,跳过空间,并获得整数为int变量。我对C++相当陌生,所以我需要帮助这样做....如何将数字读入单个char变量,并将其转换为整型变量?任何帮助将是伟大的!谢谢

回答

1

streams移动,因为你读他们。这意味着当您从流中读取F时,下一个输入是integer。而且,由于他们在格式化输入工作,当您使用>>

while(instream >> charVariable)){ 
    switch(charVariable){ 
    case 'F': //do the forward command 
     int nr; 
     instream >> nr; 
     // do something with number. 
     break; 
    ... 
    } 
} 
+0

那么,iss,nr和数字是什么? – PulsePanda 2013-05-09 20:22:39

+0

@wbAnon'iss'只是一个错字,'nr'是一个'int','numbers'是一个整数的“向量”,但我认为你不需要收集这些数字,或者你呢? – stardust 2013-05-09 20:24:58

+0

我这样做,数字是向前移动的数量 – PulsePanda 2013-05-09 20:25:59

0

基本上没有文件流和I/O流之间没有巨大的差异流会跳过空白。你可以做到以下几点:

while(!instream.eof()) 
{ 
    char command; 
    instream >> command; 
    switch(command) 
    { 
     case 'F': 
      int F_value; 
      instream >> F_value; 
      forward(F_value); 
      break; 

     //... 
    } 
} 
0

由于使用可大于一个字符的数字(即“10”代表2个字符),这将是最好只使用一个普通整数变量。

int n; 
... 
instream >> n; //if your switch statement is working this goes inside the 'F' case 

然后你可以用n来做你想要的(在你将下一个整数读入n之前)。