我有一个c ++程序,它读取文本文件,然后将该文本文件转换为字符串。然后,它使用strncpy将字符串转换为字符数组。我已经在strncpy上看到了stackoverflow问题并采取了必要的预防措施,以避免在创建数组时引起的问题。有人可以解释为什么它仍会导致堆栈错误。
#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;
}
答案 0 :(得分:3)
此:
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
答案 1 :(得分:1)
C ++不支持C语言中的可变长度数组功能.VLA是C.1999的标准功能,也是C.2011中的可选功能。
如果要将字符串内容的副本复制到动态大小的char
数组中,可以使用vector
:
std::vector<char> lyrics_(song.begin(), song.end());
lyrics_.push_back('\0');
std::cout << &lyrics_[0];