【发布时间】:2017-06-28 09:25:44
【问题描述】:
您好,我在这个项目上遇到了一些问题。假设从文本文件中获取一个句子,然后将其添加到 char* 数组 []。我的 switch 语句中的声明部分有问题。当单词长度为 3 个字符时,它会将数组中的所有元素替换为最后一个适合的元素。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int length(const char *a){
int counter=0;
while(a[counter]!= NULL){
counter++;
}
return counter;
}
int main() {
ifstream file;
file.open("C:\\Users\\casha\\Desktop\\group_project1\\message.txt");
string line;
while(!file.eof()){
getline(file,line);
}
const char* message = line.c_str();
const char *words[9];
words[0]= line.substr(0,4).c_str();
int pos = 0;
int counter = 0;
int wordscounter=0;
while(pos<=length(message)){
if(message[pos]== ' ' || message[pos]== NULL){
switch(counter){
case 3 :
words[wordscounter] = line.substr(pos- counter,counter).c_str();
wordscounter++;
break;
case 4 :
words[wordscounter] = line.substr(pos-counter,counter).c_str();
wordscounter++;
break;
case 5 :
words[wordscounter] = line.substr(pos-counter,counter).c_str();
wordscounter++;
break;
}
counter=0;
pos++;
}
else{
pos++;
counter++;
}
}
for(int x=0;x<=8;x++){
cout << words[x] << endl;
}
应该这样输出
The
quick
brown
fox
jumps
over
the
lazy
dog
而是产生:
dog
jumps
jumps
dog
jumps
lazy
dog
lazy
dog
我读过一些关于未分配内存的文章,我是 C++ 新手,因此感谢您的帮助 提前致谢 !
编辑 --
如果我像这样手动将值分配给数组
words[3] = line.substr(3,5).c_str();
然后它将打印正确的输出。 那我用这个方法和我的switch语句有什么区别,都是一样的赋值???
【问题讨论】:
-
“然后它会打印正确的输出......” - 你正在滑冰未定义的行为。考虑
line.substr(3,5).c_str()调查substr返回的内容(剧透:std::string)。现在问问自己,在该声明之后返回的std::string会发生什么。这是一个临时的,除了存储一个指向其内部字符串的 const 指针之外,您不会做任何事情,这会在下一条语句中悬空。对于我的一生,我无法理解为什么你的任务是将char*存储在一个数组中,而std::string中的std::vector在现代C++ 中更为常见。 -
@WhozCraig 感谢您的回复。我想我知道你在说什么。那么我将如何处理分配给 char* 数组而不让字符串悬在语句之外。哈哈我不选作业。
-
管理完全不同的分配技术。这完全取决于你被分配的任务的条件。正如我所说,
std::vector<std::string>可以让整个事情变得简单,但最终很可能不会出现在你的导师提供的选项菜单上(不需要任何char*处理)。跨度> -
@WhozCraig 不幸的是,我们有非常严格的规则要遵循,我必须使用 char* 数组。
标签: c++ pointers char c-strings