【发布时间】:2015-07-16 16:05:32
【问题描述】:
在做一个小项目时,我想我可以用这样的一点代码生成“随机”文件名,
std::cout << "image"+rand()%255 << std::endl;
我得到的输出对我来说毫无意义。它们似乎是错误消息的随机部分。
例如这段代码:
int main()
{
while(1){
std::cout << "image" + rand() % 255 << std::endl;
}
return 0;
}
产生像这样的胡言乱语:
> ge
>
> n
>
>
> i
>
>
> ring too long
>
> U
>
>
>
>
>
> &
>
> n
> _
> o
> string position
> e
> lid string position
> i
>
>
>
>
> U
> g
> invalid string position
>
> U
> ing position
>
>
> &
>
>
>
>
> ring position
> !
> n
>
> oo long
>
>
>
>
>
> o
> position
以及 QtCreator 中更复杂的一段代码(在主循环中使用相同的 cout rand endl 语句)
> atform\mainwindow.cpp:210
>0
>I , null image received
>indow.cpp:210
>(QImage)
>dImage(QImage)
>, error: image not read from file!
> updatePlayerUI , null image received
>updatePlayerUI(QImage)
>ow.cpp:210
>dImage(QImage)
>ot chosen
>s not chosen
>og, error: image not read from file!
> was not chosen
>age not read from file!
>r: image not read from file!
>neDataPlatform\mainwindow.cpp:210
>error: image not read from file!
这是什么原因?
【问题讨论】:
-
仅供参考:不再建议使用 rand()。请改用
库。 -
这个问题没有得到很好的研究。你不能只是把一些你不理解的非常复杂的东西全部扔到一个问题中。您应该尝试缩小问题范围并将其隔离。例如,您可以/应该先尝试
std::cout << "image"+10 << std::endl;,看看它是否符合您的想法,然后再考虑rand()。