为什么它在不同 ide 在线或不在线时有不同的行为
why it has different behavior in different ide online or not
假设这段代码:
#include <iostream>
using namespace std;
int letters_counted_in_text( std::string const&text ) {
int count = 0;
string abc = "abcdefghijklmnñopqrstuvwxyzáéíóúABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ";
for( unsigned i=0; i<text.length(); ++i )
for( unsigned j=0; j<abc.length(); ++j )
if( text.at( i )==abc.at( j ) )
{
count++;
j=abc.length();
}
return count;
}
int main() {
// your code goes here
string test = "Hola, cómo estás";
cout << letters_counted_in_text(test);
return 0;
}
为什么它在 codechef
中有不同的行为:
输出:
13
但是在ideone
中是:
输出:
15
in cpp.sh
OutPut: 是 15
这种行为是为了什么?抱歉我的英语不好希望你能理解我说的?
您似乎遇到了字符编码问题。在您的源代码中使用的几个字符不是 ASCII 的成员。这让您对扩展 ASCII 的不同编码和不同解释持开放态度。
例如,将您的源代码保存为 UTF-8,然后使用仅读取原始 ASCII 的编辑器打开,字符串就出来了
string abc = "abcdefghijklmnñopqrstuvwxyzáéÃóúABCDEFGHIJKLMNÑOPQRSTUVWXYZÃÉÃÓÚ";
和
string test = "Hola, cómo estás";
这将 15 个字符放入 test
中,这些字符也在 abc
中,因为有些字符占用了超过一个字节。使用 std::wstring
而不是 std::string
应该有助于解决这个问题,但您还需要使用 widechar 字符串文字
wstring abc = L"abcdefghijklmnñopqrstuvwxyzáéíóúABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ";
和
wstring test = L"Hola, cómo estás";
当然还有
int letters_counted_in_text(std::wstring const&text)
因为我们需要将wstring
传递给函数。
在 ideone 上:http://ideone.com/fAVPKt
现在我们剩下的问题是,"Why did this work on CodeChef?"
假设这段代码:
#include <iostream>
using namespace std;
int letters_counted_in_text( std::string const&text ) {
int count = 0;
string abc = "abcdefghijklmnñopqrstuvwxyzáéíóúABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ";
for( unsigned i=0; i<text.length(); ++i )
for( unsigned j=0; j<abc.length(); ++j )
if( text.at( i )==abc.at( j ) )
{
count++;
j=abc.length();
}
return count;
}
int main() {
// your code goes here
string test = "Hola, cómo estás";
cout << letters_counted_in_text(test);
return 0;
}
为什么它在 codechef
中有不同的行为:
输出:
13
但是在ideone
中是:
输出:
15
in cpp.sh
OutPut: 是 15
这种行为是为了什么?抱歉我的英语不好希望你能理解我说的?
您似乎遇到了字符编码问题。在您的源代码中使用的几个字符不是 ASCII 的成员。这让您对扩展 ASCII 的不同编码和不同解释持开放态度。
例如,将您的源代码保存为 UTF-8,然后使用仅读取原始 ASCII 的编辑器打开,字符串就出来了
string abc = "abcdefghijklmnñopqrstuvwxyzáéÃóúABCDEFGHIJKLMNÑOPQRSTUVWXYZÃÉÃÓÚ";
和
string test = "Hola, cómo estás";
这将 15 个字符放入 test
中,这些字符也在 abc
中,因为有些字符占用了超过一个字节。使用 std::wstring
而不是 std::string
应该有助于解决这个问题,但您还需要使用 widechar 字符串文字
wstring abc = L"abcdefghijklmnñopqrstuvwxyzáéíóúABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ";
和
wstring test = L"Hola, cómo estás";
当然还有
int letters_counted_in_text(std::wstring const&text)
因为我们需要将wstring
传递给函数。
在 ideone 上:http://ideone.com/fAVPKt
现在我们剩下的问题是,"Why did this work on CodeChef?"