C++ 在 cin 时忽略特定字符
C++ ignore specific character while cin
我的输入如下:
4 5i 6 7i
不是用字符串查找和替换,
我想将这些单独的值存储在双
但偷看和忽略'i'
所以
双 a = 4,b = 5,c = 6,d = 7
下面丑陋的代码是我正在做的事情
我迷路了,不胜感激
谢谢!
char c, real[1024], img[1024];
int i = 0;
bool flag = false,
flag2 = false;
while( c = input.get() )
{
if( input.peek() == ' '){
i = 0;
flag2 = true;
}
if( !flag2 ){
real[ i++ ] = c;
}else{
img[ i++ ] = c;
}
if( flag )
{
break;
}
while( input.peek() == 'i' )
{
if( input.peek() == 'i' )
{
flag = true;
i = 0;
flag2 = true;
}if( input.peek() == ' ' )
{
i = 0;
flag2 = true;
}
input.ignore(1, 'i');
}
}
if( flag ){
obj.doubleValueA = 0.0 ;
obj.doubleValueB = atof( real );
return input;
}else{
obj.doubleValueA = atof( real );
obj.doubleValueB = atof( img );
}
return input; // enables cin >> a >> b >> c
#include<iostream>
#include<vector>
#include<sstream>
#include<ctype>
#include<string>
using namespace std;
int parseNumber( string number )
{
unsigned i = 0;
// Find the position where the character starts
while ( i < number.size() && isdigit( number[i] )
{
i++;
}
number = number.substr( 0, i );
// Retrieve the number from the string using stringstream
stringstream ss( number );
int result;
ss >> result;
// Return the result
return result;
}
int main()
{
string input;
getline( cin, input );
stringstream ss( input );
string number;
vector<int> complexNumbers;
while ( ss >> number )
{
complexNumbers.push_back( parseNumber( number ) );
}
for ( unsigned i = 0; i < complexNumbers.size(); i++ )
{
cout << complexNumbers[i] << " ";
}
}
我的输入如下:
4 5i 6 7i
不是用字符串查找和替换,
我想将这些单独的值存储在双
但偷看和忽略'i'
所以
双 a = 4,b = 5,c = 6,d = 7
下面丑陋的代码是我正在做的事情
我迷路了,不胜感激
谢谢!
char c, real[1024], img[1024];
int i = 0;
bool flag = false,
flag2 = false;
while( c = input.get() )
{
if( input.peek() == ' '){
i = 0;
flag2 = true;
}
if( !flag2 ){
real[ i++ ] = c;
}else{
img[ i++ ] = c;
}
if( flag )
{
break;
}
while( input.peek() == 'i' )
{
if( input.peek() == 'i' )
{
flag = true;
i = 0;
flag2 = true;
}if( input.peek() == ' ' )
{
i = 0;
flag2 = true;
}
input.ignore(1, 'i');
}
}
if( flag ){
obj.doubleValueA = 0.0 ;
obj.doubleValueB = atof( real );
return input;
}else{
obj.doubleValueA = atof( real );
obj.doubleValueB = atof( img );
}
return input; // enables cin >> a >> b >> c
#include<iostream>
#include<vector>
#include<sstream>
#include<ctype>
#include<string>
using namespace std;
int parseNumber( string number )
{
unsigned i = 0;
// Find the position where the character starts
while ( i < number.size() && isdigit( number[i] )
{
i++;
}
number = number.substr( 0, i );
// Retrieve the number from the string using stringstream
stringstream ss( number );
int result;
ss >> result;
// Return the result
return result;
}
int main()
{
string input;
getline( cin, input );
stringstream ss( input );
string number;
vector<int> complexNumbers;
while ( ss >> number )
{
complexNumbers.push_back( parseNumber( number ) );
}
for ( unsigned i = 0; i < complexNumbers.size(); i++ )
{
cout << complexNumbers[i] << " ";
}
}