本文介绍了格式化输出c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想做一些漂亮的格式化。我有几行想互相交流。获取前两行。打印第二行中的字符乘以第一行中的整数。用星号分隔所有字符。最后一个字符打印后没有星号。移动到下一个整数和字符。将它们打印在单独的行上。对整个列表执行此操作。我遇到的问题是将它们打印在单独的行上。示例:

  5 

2

3

所需的输出:

 !*!*!*!*! 
?*?
#*#*#

我的输出:

 !*!*!*!*!*?*?*#*#*#* 

下面是我的代码。还要提到的另一件事是,我正在从一个单独的文本文件中读取有关字符和数字的数据。因此,我正在使用getline函数。



下面是其中的一部分代码:

  ifstream文件
File.open( NumbersAndCharacters.txt)
字符串Number;
string字符;
while(!File.eof(){
getline(File,Number);
getline(File,Character);
//几行字符串流操作
for(int i = 0; i< = Number; i ++){
cout<< Character<< *;} //结束,我认为这是
///问题是
} // end而
File.close();
返回0;

错误在哪里?是循环吗?还是我不明白getline?



它应该打印 endl或

感谢大家的响应!

解决方案

您尚未显示代码,但是这里出现的问题是,您每次打印字符时都忘记了添加新行,例如,您可能已经完成了:

  std :: cout<<!; 

在这种情况下,您忘记添加新行('\n'),因此您在此处有两个选择:首先自己插入新行:

  std :: cout<< !\n; 

std :: endl;

  std :: cout<< ! << std :: endl; 

有关两者的比较,请参见和。没有进一步的描述,或更重要的是,您的代码似乎无法正常运行,我们将无法提出建议或解决您的问题。


Wanting to do some fancy formatting. I have several lines that I want to interact with each other. Get the first two lines. Print out the character in the second line times the integer in the first line. Seperate them all with a asterisk character. No asterisk after the final character is printed. Move onto the next integer and character. Print them on a separate line. Do this for the whole list. The problem I am having is printing them on separate lines. Example:

5
!
2
?
3
#

Desired output:

!*!*!*!*!
?*?
#*#*#

My output:

!*!*!*!*!*?*?*#*#*#*

Below is my code. Another thing to mention is that I am reading the data about the characters and numbers from a separate text file. So I am using the getline function.

Here is a chunk of the code:

ifstream File
File.open("NumbersAndCharacters.txt")
string Number;
string Character;
while(!File.eof(){
  getline(File, Number);
  getline(File, Character);
//a few lines of stringstream action
  for (int i=0; i<=Number; i++){
      cout<<Character<<"*";}//end for. I think this is where
                            //the problem is.
  }//end while
File.close();
return 0;

Where is the error? Is it the loop? Or do I not understand getline?

It should be printing an "endl" or "\n" after each multiplication of the character is done.

Thanks to everyone for the responses!

解决方案

You have not shown your code yet, but what seems to be the issue here is that you simply forgot to add a new line every time you print your characters. For example, you probably have done:

std::cout << "!";

Well, in this context you forgot to add the new line ('\n'), so you have two options here: first insert the new line yourself:

std::cout << "! \n";

Or std::endl;

std::cout << "!" << std::endl;

For comparison of the two, see here and here. Without further description, or more importantly your code that doesn't seem to work properly, we can't make suggestions or solve your problem.

这篇关于格式化输出c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 13:21