问题是operator >>
在流中遇到空格字符时停止输入字符串。您应该使用标准功能std::getline
。
考虑到要显示一个字符串,不需要定义一个数组。该任务可以在不使用数组的情况下完成。
这是一个示范程序。
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
while (true)
{
std::cout << "Number of rows (0 - exit): ";
unsigned int rows;
if (not (std::cin >> rows) or (rows == 0)) break;
std::cout << "Number of columns (0 - exit): ";
unsigned int cols;
if (not (std::cin >> cols) or (cols == 0)) break;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Type in text: (Enter - exit): ";
std::string text;
std::getline(std::cin, text);
if (text.empty()) break;
std::cout << std::endl;
std::string::size_type n = text.size();
n = std::min<std::string::size_type>(n, cols * rows);
for (std::string:: size_type i = 0; i < n; i++)
{
std::cout << text[i];
std::cout << ((i + 1) % cols == 0 ? '\n' : ' ');
}
std::cout << std::endl;
}
return 0;
}
它的输出可能看起来像
Number of rows (0 - exit): 3
Number of columns (0 - exit): 4
Type in text: (Enter - exit): HarryPotter
H a r r
y P o t
t e r
Number of rows (0 - exit): 2
Number of columns (0 - exit): 6
Type in text: (Enter - exit): HarryPotter
H a r r y P
o t t e r
Number of rows (0 - exit): 6
Number of columns (0 - exit): 2
Type in text: (Enter - exit): HarryPotter
H a
r r
y P
o t
t e
r
Number of rows (0 - exit): 4
Number of columns (0 - exit): 4
Type in text: (Enter - exit): Antonella Masini
A n t o
n e l l
a M a
s i n i
Number of rows (0 - exit): 0
您可以替代这种说法
if (not (std::cin >> rows) or (rows == 0)) break;
对于这一说法
if (!(std::cin >> rows) || (rows == 0)) break;
如果编译器不编译的第一个语句。如果您使用MS VC++,那么在项目的属性中,您应该关闭使用语言扩展(C++,language),并且语句将被编译。
如何定义可变文本?如果iif二维数组的总元素大于文本中的字符数,该怎么办? –
你也应该添加null终止到输入文本的末尾 – Raindrop7
我怀疑['std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline)很快会在你的未来。 – WhozCraig