在for循环c ++中打印字符
Print character in a for loop c++
这是一个非常基本的问题,因为我是 C++ 语言的新手,但我有一个程序需要一个函数来在 for 循环中打印单个字符。我的代码如下所示:
void printBar(const char symbol, int count){
for (int i = 0;i <= count; i++){
cout << symbol;
}
}
我的主要功能是:
int main(){
int size = 8;
const char* sym = "*":
printBar(sym,size);
我希望我的结果如下所示:
********
我做错了什么?
初学者有错字
const char* sym = "*":
^^^
要有一个分号。
函数中的循环应该如下所示
void printBar(const char symbol, int count){
for (int i = 0; i < count; i++){
^^^^^^^^^
cout << symbol;
}
}
第一个参数声明中的限定符 const 可能会被删除。
void printBar(char symbol, int count){
如果变量sym
声明为
const char* sym = "*":
那么函数应该这样调用
printBar(*sym,size);
或
printBar(sym[0],size);
也就是说,您只需要向函数传递一个字符而不是指针。
另一种写函数的方法可以看演示程序中所示
#include <iostream>
#include <iomanip>
std::ostream & printBar( char symbol, size_t count, std::ostream &os = std::cout )
{
if ( count )
{
os << std::setw( count ) << std::setfill( symbol ) << symbol;
}
return os;
}
int main()
{
size_t size = 8;
const char *sym = "*";
printBar( *sym, size ) << std::endl;
return 0;
}
它的输出是
********
你应该说出了什么问题。错误,输出错误....但我可以猜到
首先这个循环是错误的
void printBar(const char symbol, int count){
for (int i = 0;i <= count; i++){
cout << symbol;
}
}
它会打印出过多的字符。你应该 i < count
其次你的函数需要一个字符,但是你传入了一个字符*
这样做
int main(){
int size = 8;
const char sym = '*':
printBar(sym,size);
这是一个非常基本的问题,因为我是 C++ 语言的新手,但我有一个程序需要一个函数来在 for 循环中打印单个字符。我的代码如下所示:
void printBar(const char symbol, int count){
for (int i = 0;i <= count; i++){
cout << symbol;
}
}
我的主要功能是:
int main(){
int size = 8;
const char* sym = "*":
printBar(sym,size);
我希望我的结果如下所示:
********
我做错了什么?
初学者有错字
const char* sym = "*":
^^^
要有一个分号。
函数中的循环应该如下所示
void printBar(const char symbol, int count){
for (int i = 0; i < count; i++){
^^^^^^^^^
cout << symbol;
}
}
第一个参数声明中的限定符 const 可能会被删除。
void printBar(char symbol, int count){
如果变量sym
声明为
const char* sym = "*":
那么函数应该这样调用
printBar(*sym,size);
或
printBar(sym[0],size);
也就是说,您只需要向函数传递一个字符而不是指针。
另一种写函数的方法可以看演示程序中所示
#include <iostream>
#include <iomanip>
std::ostream & printBar( char symbol, size_t count, std::ostream &os = std::cout )
{
if ( count )
{
os << std::setw( count ) << std::setfill( symbol ) << symbol;
}
return os;
}
int main()
{
size_t size = 8;
const char *sym = "*";
printBar( *sym, size ) << std::endl;
return 0;
}
它的输出是
********
你应该说出了什么问题。错误,输出错误....但我可以猜到
首先这个循环是错误的
void printBar(const char symbol, int count){
for (int i = 0;i <= count; i++){
cout << symbol;
}
}
它会打印出过多的字符。你应该 i < count
其次你的函数需要一个字符,但是你传入了一个字符*
这样做
int main(){
int size = 8;
const char sym = '*':
printBar(sym,size);