如何用c ++创建结果空间 [英] how to make space in result with c++

查看:92
本文介绍了如何用c ++创建结果空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include     stdafx.h 
#include < iostream >
使用 命名空间标准;

int main()
{
int A,bو,C;
cout<< 输入第一个数字:;
cin>> a;
cout<< 输入第二个数字:;
cin>> b;

c = a * b;

cout<< 结果为:<< c;

}





当c = a * b

a = 75

b = 86



注意。结果将显示为这样的6540

但是我想在这个数字之间留出空间6 5 4 0; nubmer之间的空格如何可以

解决方案

< blockquote>类似C的方法是:

 ... 
const int size = 20 ;
char buffer [size];
int n = snprintf(缓冲区,大小, %d,c); // 使用安全功能:s n printf,不要使用sprintf
断言(n> = 0 ); // 格式错误由负值表示
assert(n< size); // n是写入的字符数,不包括终止空字符
的类=code-keyword>( int i = 0 ; i< n; ++ i)cout<< buffer [i]<< ' ';



它的作用:

1)将 c 写入字符数组( buffer )。

2)确保你没有写过缓冲区末尾(使用 snprintf [ ^ ])

3)make确保转换不需要比缓冲区提供的更多字符(请记入返回值并断言 [ ^ ]写作并不期望更大的缓冲区)。

4)最后写下每个字符后跟一个空格



类似C ++的方法是使用osstreamstream [ ^ ]。

 ... 
ostringstream oss;
oss<< C;
断言(oss.good()); // 无格式错误
// C ++ 11版本
for char ch:oss.str())cout<< ch<< ' ';
// 基于迭代器的版本
string s = oss.str();
for (string :: iterator it = s.begin(); it!= s.end(); ++ it)cout<< *它<< ' ';



干杯
Andi


转换为字符串(提示:查看 sprintf )然后遍历输出每个字符后跟空格的字符。 />
问候,

Ian。


#include "stdafx.h"
#include <iostream>
using namespace std;

int main ()
{
    int a,bو,c;
    cout<<"Enter the First Number : ";
    cin>>a;
    cout<<"Enter the Second Number : ";
    cin>>b;

    c=a*b;

    cout<< "The Result is : "<<c;

}



when c=a*b
a = 75
b = 86

attention. the result will appear like this 6540
but i want space between the number like this 6 5 4 0 ;OK space between nubmer how can

解决方案

A C-like approach was:

...
const int size = 20;
char buffer[size];
int n = snprintf(buffer, size, "%d", c); // use the safe function: snprintf, do not use sprintf
assert(n >= 0);   // format error is indicated by a negative value
assert(n < size); // n is the number of characters written, excluding the terminating null-character
for(int i = 0; i < n; ++i) cout << buffer[i] << ' ';


What it does:
1) write the c into a character array (buffer).
2) make sure you do not write past the buffer end (use snprintf[^])
3) make sure the conversion does not need more characters than provided by the buffer (take in count the return value and assert[^] that writing was not expecting a larger buffer).
4) finally write each character followed by a space

A C++ like approach was to use ostringstream[^].

...
ostringstream oss;
oss << c;
assert(oss.good()); // no format error
// C++11 version
for(char ch: oss.str()) cout << ch << ' ';
// iterator based version
string s = oss.str();
for(string::iterator it = s.begin(); it != s.end(); ++it) cout << *it << ' ';


Cheers
Andi


Convert to a string ( hint: look at sprintf ) then iterate through the characters outputting each one followed by a space.
Regards,
Ian.


这篇关于如何用c ++创建结果空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆