字符数组的问题 [英] Char array issue

查看:79
本文介绍了字符数组的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编辑使用以下C ++ code linux的我自己和Vi文件。我试图使用命名字符数组中的文件,但是当我试图从字符串复制到一个动态的字符数组,我在array.What年底得到奇怪的字符是什么原因?我怎么能解决这个问题?对不起,它没有让我张贴图片,所以我复制了我对屏幕并粘贴它
谢谢

 的新路径[0] ='V';
  的新路径[1] ='我';
  的新路径[2] =''; 的for(int i = 0; I< fileName.length();我++)
 {
    stringLenght = 3 +我;
的新路径[stringLenght] =(char)的文件名[我]
 }
     COUT<<&的新路径LT;<长:<< fileName.length()<< ENDL;文件在当前目录下面上市;main.cpp中
a.cpp
a.cpp。#^ h ???你想要哪个文件进行编辑?:a.cpp位置: 。 Locationlength:0六a.cpp#{长度:5


解决方案

的std :: cout.operator<<(字符*)(你的的char [] 数组衰变为的char * )使用 \\ 0 作为它的终结。看来你不追加的空虽然。

pretty大致相同的问题,因为<一href=\"http://stackoverflow.com/questions/20268769/why-do-i-get-garbage-value-when-output-character-array-to-console/20268786#20268786\">here.

一个简单的解决方法是手动添加 \\ 0 来的字符数组的结尾。

I am trying to edit my own files with Vi on linux using the following C++ code. I am trying to name the files using character array, but when I am trying to copy from string to a dynamic character array, I get weird characters at the end of the array.What is the reason? How could I fix it? Sorry It didnt let me post the picture so i copied what i had on screen and pasted it Thank you

  newPath[0] = 'v';
  newPath[1] = 'i';
  newPath[2] = ' ';

 for(int i = 0 ; i < fileName.length(); i++)
 {
    stringLenght =3 + i;
newPath[stringLenght] = (char)fileName[i];
 }
     cout<<newPath<<" length:"<<fileName.length()<<endl;

Files are on current directory are listing below;

main.cpp   
a.cpp 
a.cpp.#h???

Which file do you want to edit?: a.cpp

location: . Locationlength:0

vi a.cpp.#�{� length:5

解决方案

std::cout.operator<<(char*) (your char[] array decays to char*) uses \0 as its terminator. It seems that you're not appending that null though.

Pretty much the same problem as here.

A simple solution is to manually add \0 to the end of your char array.

这篇关于字符数组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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