![](/img/trans.png)
[英]Converted string to char, when i cout the char it is correct but when I use chdir with the char it does not work?
[英]std::rename() file wont work when using a char variable as arguments (string converted to char)
我嘗試了一下,但沒有在字符串tablename4
和tablename5
的開頭和結尾添加"\\""
,然后再將其轉換為char, rename()
函數仍然不起作用,僅通過輸入實際文件名即可作為rename()參數,但這不是我想要的,我想使用char變量
完整的編譯代碼:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
using std::string;
int main()
{
std::string tablename4 = "hello.txt";
ifstream in4(tablename4);
ofstream out8("temp2.txt");
std::string convertthis2;
convertthis2 = "\"" + tablename4 + "\"";
char * tochar2 = new char[convertthis2.length()];
strcpy_s(tochar2, (convertthis2.length() + 1), convertthis2.c_str());
std::string convertthis3;
std::string tablename5 = "temp2.txt";
convertthis3 = "\"" + tablename5 + "\"";
char * tochar3 = new char[convertthis3.length()];
strcpy_s(tochar3, (convertthis3.length() + 1), convertthis3.c_str());
in4.close();
out8.close();
rename(tochar3, tochar2);
//below is testing to see if it converted right, but these print out fine, as "hello.txt" and "temp2.txt"
//but i tried it with and without the quotation marks, rename() still doesnt work
cout << tochar2 << " " << tochar3;
return 0;
}
略微簡化並糾正2個錯誤:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
using std::string;
int main()
{
std::string tablename4 = "hello.txt";
ifstream in4(tablename4);
ofstream out8("temp2.txt");
std::string convertthis2 = string("\"") + tablename4 + "\"";
std::string tablename5 = "temp2.txt";
std::string convertthis3 = string("\"") + tablename5 + "\"";
in4.close();
out8.close();
rename(convertthis3.c_str(), convertthis2.c_str());
//below is testing to see if it converted right, but these print out fine, as "hello.txt" and "temp2.txt"
//but i tried it with and without the quotation marks, rename() still doesnt work
cout << convertthis2 << " " << convertthis3 << endl;
return 0;
}
問題是您要分配一個字節數組,該數組等於string
對象的長度,然后將這些數組用作c樣式字符串。 但是,c風格的字符串必須有一個結尾的零,您不能添加該結尾-從而導致不確定的行為。
注意上面的.c_str()成員變量的使用。 它確實滿足您的要求-以安全的方式使std :: string看起來像c樣式的字符串。
可以避免這種情況的想法是,如果您發現自己編寫C代碼,那是因為您將從閱讀stl文檔中受益。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.