为什么这个C ++程序不起作用? [英] Why won't this C++ program work?

查看:80
本文介绍了为什么这个C ++程序不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在程序中想要的不是

cout << "Text";



打印出来:文字,我想要另一个命令,如cout<<这将打印出每个字符作为快捷方式而不是


which prints out: Text, I want another command like cout << that will print out each character as a shortcut instead of

char str[] = "Hello world!";
    int i = 0;
    
    while (str [i] != '\0')
    {
        cout << str[i++] << ' ';
        cout.flush();
        usleep (100000);
        cout << ' ';
    }



所以我可以将str设置为变量并轻松访问,或者其他一些更短的方法。



~谢谢!



我尝试过:




So i can set str to a variable and easly access, or some other shorter way to do so.

~Thanks!

What I have tried:

#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;

int main ()
{
    char str[] = "Hello world!";
    int i = 0;
    
    while (str [i] != '\0')
    {
        cout << str[i++] << ' ';
        cout.flush();
        usleep (100000);
        cout << ' ';
    }
    return 0;
}

int main ()
{
    
    char str[] = "Hello world!";
    int i = 0;
    
    while (str [i] != '\0')
    {
        cout << str[i++] << ' ';
        cout.flush();
        usleep (100000);
        cout << ' ';
    }
    str [] = "Hello world2!";
    return 0;
}

这个返回一个错误。

推荐答案

当你在里面存储新值时,C ++不会动态调整数组的大小。 />
C++ do not dynamically resize arrays when you store new values inside.
char 
str[] = "Hello world!";
...
str[] = "Hello world2!";  // so this will not fit in actual array, 1 chat too long.


您正在使用wrog类型进行操作。使用std :: string而不是char []。
You are using the wrog type for your operations. Use std::string instead of the char[].


这篇关于为什么这个C ++程序不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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