2010-09-15 177 views
1

我初始化字符串,如下所示:为什么我的std :: string被截断?

std::string myString = "'The quick brown fox jumps over the lazy dog' is an English-language pangram (a phrase that contains all of the letters of the alphabet)"; 

和myString的最终被切断这样的:

“敏捷的棕色狐狸跳过 懒狗”是英语语言? 全字母短句(包含

我在哪里可以设置大小限制的一句话 我尝试没有成功如下:

std::string myString; 
myString.resize(300); 
myString = "'The quick brown fox jumps over the lazy dog' is an English-language pangram (a phrase that contains all of the letters of the alphabet)"; 

非常感谢!

+4

字符串没有大小限制(至少不是小到100的一个,可能会有兆字节的实现限制)。该错误在您的代码中的其他地方。写一个简短的程序来展示问题,然后发布。您的终端是否有100个字符?截断可能发生在输出上(尽管我不知道什么终端截断而不是包装)。 – 2010-09-15 12:28:34

+1

字符串不应该被切断。你如何检查/显示它? – 2010-09-15 12:29:02

+4

你怎么知道它被切断?你打印出来了,还是看着调试器(哪一个?)? – 2010-09-15 12:29:45

回答

1

当然,它只是调试器切断它(xcode)。我刚刚开始使用xcode/C++,所以非常感谢快速回复。

0

请尝试以下(在调试模式):

assert(!"Congratulations, I am in debug mode! Let's do a test now...") 
std::string myString = "'The quick brown fox jumps over the lazy dog' is an English-language pangram (a phrase that contains all of the letters of the alphabet)"; 
assert(myString.size() > 120); 

是否(第二)断言失败?

+1

您可能会尝试在调试中执行,否则assert调用将被编译器忽略。 – ereOn 2010-09-15 12:56:57

+0

@ereOn是的。我添加了一个额外的测试来测试我们是否处于调试模式。 – 2010-09-15 13:27:42

+0

'assert()'抱怨错误表达后,它调用'abort()'。 – aschepler 2011-11-05 15:49:16

0

你确定吗?

kkekan> ./a.out 
'The quick brown fox jumps over the lazy dog' is an English-language pangram (a phrase that contains all of the letters of the alphabet) 

没有理由为什么会发生这种情况!

0

当打印或显示文本时,输出机器缓冲输出。你可以告诉它冲洗缓冲器由输出(显示所有剩余的文本)“\ n”或使用std::endl或执行flush()方法:

#include <iostream> 
using std::cout; 
using std::endl; 

int main(void) 
{ 
    std::string myString = 
    "'The quick brown fox jumps over the lazy dog'" // Compiler concatenates 
    " is an English-language pangram (a phrase"  // these contiguous text 
    " that contains all of the letters of the"  // literals automatically. 
    " alphabet)"; 
    // Method 1: use '\n' 
    // A newline forces the buffers to flush. 
    cout << myString << '\n'; 

    // Method 2: use std::endl; 
    // The std::endl flushes the buffer then sends '\n' to the output. 
    cout << myString << endl; 

    // Method 3: use flush() method 
    cout << myString; 
    cout.flush(); 

    return 0; 
} 

有关缓冲区的详细信息,搜索堆栈溢出为“C++输出缓冲”。

相关问题