为什么我的std :: string被切断了?

时间:2010-09-15 12:25:36

标签: c++ string resize standard-library

我按如下方式初始化字符串:

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最终会被切断:

  

'快速的棕色狐狸跳过了   懒狗'是一种英语   pangram(包含

的短语

我在哪里可以设置大小限制? 我尝试了以下但没有成功:

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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);

(第二个)断言是否失败?

答案 2 :(得分: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)

没有充分的理由说明为什么会发生这种情况!

答案 3 :(得分: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 ++输出缓冲区”的堆栈溢出。