gpt4 book ai didi

c++ - 使用 getline() 读取单引号

转载 作者:行者123 更新时间:2023-11-28 07:19:08 25 4
gpt4 key购买 nike

我正在做 UVa Problem 10082,我正在尝试读入一些样本输入来测试我的解决方案。但是,当我阅读文本 '''CCC 时,它会输出 ;;XXX。请注意,只有 2 个分号,而应该有 3 个,因为输入中有 3 个单引号。为什么 getline() 会忽略第一个单引号?

这是我的代码:

#include <iostream>
#include <string>

using namespace std;

char mapToWertyu(char c)
{
char newC = c;
char wertyu[] = {'1','2','3','4','5','6','7','8','9','0','-','=',
'Q','W','E','R','T','Y','U','I','O','P','[',']','\\',
'A','S','D','F','G','H','J','K','L',';','\'',
'Z','X','C','V','B','N','M',',','.','/'};
char qwerty[] = {'~','1','2','3','4','5','6','7','8','9','0','-','=',
'Q','W','E','R','T','Y','U','I','O','P','[',']','\\',
'A','S','D','F','G','H','J','K','L',';','\'',
'Z','X','C','V','B','N','M',',','.','/'};
if(c=='A' || c=='Q' || c=='Z')
return c;

for(int i = 0; i < 47; ++i)
{
if(wertyu[i]==c)
{
newC = qwerty[i];
break;
}
}
return newC;
}

int main()
{
string input;
while(cin.peek()!=-1)
{
getline(cin,input);
for(int i = 0; i < input.length(); ++i)
{
if(input[i]!='\\')
cout << mapToWertyu(input[i]);
}
cin.ignore(1,'\n');
cout << endl;
}
return 0;
}

最佳答案

因为你告诉它。你在做什么 std::cin.ignore( 1,
'\n' )
应该做,如果不是忽略一个字符。 std::getline提取 '\n' 字符,即使它没有放入字符串。

对于其余部分,您没有正确输入。对于初学者,std::cin.peek() 将返回一个整数范围 [0...UCHAR_MAX]EOFEOF 通常定义为-1,但这当然不能保证。但更一般地说:为什么不使用通常的成语:

while ( std::getline( std::cin, input ) ) {
// ...
}

每次你在 mapToWertyu 中构建数组叫它。那绝对不是您想要做的。你可以只使用一个静态数组,直接由字符索引,这个错误确实使程序依赖于编码。到但是,使用两个数组:

static char const wertyu[] = { ... };
static char const qwerty[] = { ... };
char const* pos = std::find( std::begin( wertyu ), std::end( wertyu ), c );
return pos == std::end( wertyu )
? c
: qwerty[ pos - std::begin( wertyu ) ];

以更简单的方式解决问题。 (而且没有需要特殊情况 'A''Q''Z'。如果你不想要对它们进行转码,只需不要将它们放在表格中即可。)

或者...

struct Map
{
char from;
char to;
};
static Map const map[] =
{
{ '1', '~' },
{ '2', '1' },
// ...
};
Map const* pos = std::find_if( std::begin( map ), std::end( map ),
[]( char ch ) { return c == ch; } );
return pos == std::end( map )
? c
: pos->to;

这具有使精确映射可见的优点。

或者,如果您 100% 确定永远不必担心线程:

struct Map
{
char from;
char to;
};
static Map map[] =
{
{ '1', '~' },
{ '2', '1' },
// ...
{ 0, 0 }
};
Map* sentinal = std::end( map ) - 1;
sentinal->to = sentinal->from = c;
Map const* pos = std::find_if( std::begin( map ), std::end( map ),
[]( Map const& entry ) { return c == entry.from; } );
return pos->to;

通过插入哨兵,您可以确定该条目将被发现。

或者您可以对 map 进行排序,并使用 std::lower_bound

还有,为什么调用函数mapToWertyu,当它映射的时候查询?

关于c++ - 使用 getline() 读取单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19774496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com