我有一个c++程序,它读取一个文本文件,然后将该文本文件转换为字符串。然后,它使用 strncpy 将字符串转换为字符数组。我已经在 strncpy 上看到了堆栈溢出问题,并采取了必要的预防措施以避免它在创建数组时导致的问题。有人可以解释为什么它仍然会导致堆栈错误。
#include <iostream>
#include <string.h>
#include <random>
#include <fstream>
#include <istream>
#include <sstream>
#include <stdio.h>
using namespace std;
int main()
{
//open a stream reader
ifstream fin;
//opens the text file in the stream reader
fin.open("songlyrics.txt");
//will be used to aggregate all characters in text file
string song;
//used as a pointer when reading each character in text file
char ch;
//while the end of file is not reached
while(!fin.eof())
{
//get the character from the file and add it to the song string
fin.get(ch);
song += ch;
}
//close the file
fin.close();
//make a character array called lyrics_ with a length of the length of song
char lyrics_[song.length()];
//use strncpy to convert song to a char array, lyrics_
strncpy(lyrics_, song.c_str(), sizeof(lyrics_));
//avoid the segmentation fault
lyrics_[sizeof(lyrics_) - 1] = 0;
cout<<lyrics_;
return 0;
}
这个:
char lyrics_[song.length()];
// ^^^^^^^^^^^^^
// not a compile-time constant
是一个可变长度数组,不是标准C++。
此外,您无需将std::string
转换为字符数组。它已经是:
char* lyrics = &song[0]; // assuming you don't append to song in the future
如果你真的想要一个单独的字符缓冲区,你必须动态分配它:
char* lyrics = new char[song.length() + 1];
memcpy(lyrics, song.c_str(), song.length() + 1); // this will copy the null terminator
delete [] lyrics; // don't forget this
C++不支持
C.1999的标准功能,也是C.2011中的可选功能。
如果要将字符串的内容复制到动态大小的char
数组中,可以使用vector
:
std::vector<char> lyrics_(song.begin(), song.end());
lyrics_.push_back(' ');
std::cout << &lyrics_[0];