C++ 从c+中的多行txt文档中读取数字+;
我正在制作一个程序,有一个.txt文件,我需要从中读取,并从中获取命令。文本文档如下所示:C++ 从c+中的多行txt文档中读取数字+;,c++,variables,casting,io,ifstream,C++,Variables,Casting,Io,Ifstream,我正在制作一个程序,有一个.txt文件,我需要从中读取,并从中获取命令。文本文档如下所示: U R F 10 D F 13 Q 我需要从中得到数字。我读取文件的方式是从名为instream的ifstream对象。目前我正在使用 while(instream.get(charVariable)){ switch(charVariable){ case 'F': //do the forward command break; ... } } forw
U
R
F 10
D
F 13
Q
我需要从中得到数字。我读取文件的方式是从名为instream
的ifstream
对象。目前我正在使用
while(instream.get(charVariable)){
switch(charVariable){
case 'F': //do the forward command
break;
...
}
}
forward命令需要获取该行,它需要读取
F
,跳过空格,并将整数放入int
变量中。我对C++相当陌生,所以我需要帮助。如何将数字读入单个char变量,读入整数变量?任何帮助都会很好!谢谢流
阅读时移动。这意味着当您从流中读取F
时,下一个输入是整数。由于它们处理格式化输入,因此当您使用>
while(instream >> charVariable)){
switch(charVariable){
case 'F': //do the forward command
int nr;
instream >> nr;
// do something with number.
break;
...
}
}
基本上,文件流和i/o流之间没有很大的区别。您可以执行以下操作:
while(!instream.eof())
{
char command;
instream >> command;
switch(command)
{
case 'F':
int F_value;
instream >> F_value;
forward(F_value);
break;
//...
}
}
由于使用的数字可以大于一个字符(即“10”是两个字符),因此最好只使用正则整数变量
int n;
...
instream >> n; //if your switch statement is working this goes inside the 'F' case
然后你可以用n做你想做的事情(在你把下一个整数读入n之前) 那么,什么是iss、nr和数字呢?@wbAnoniss
只是一个打字错误,nr
是一个int
,而numbers
是一个向量的int,但我认为你不需要收集数字,是吗?我需要,数字是移动的量forward@wbAnon你前进到底是什么意思?nvm,很好。我接受了你所做的,并改变了一点,现在它就像一个魅力!谢谢你,伙计!