2017-03-05 74 views
1

我在一个函数里面添加一个整数给一个叫做输出的字符串引用。我在另一个函数中创建了一个名为output的String,并且通过引用该函数的参数来传递它。但是,当我尝试打印它时,我收到了一堆奇怪的符号 。我试图用sstream输出,但它没有工作:如何打印一个字符串里面有整数C++

Student.cc

void Student::makeString(string& output){ 
    output += fname + "\t"; // this is a string 
    output += lname + "\t"; // this is a string 
    output += id + "\t"; // this is an int 
} 

IO.cc

void IO::printInfo(Student& student){ 
    string output = ""; 
    student.makeString(output); 

    // doesnt work 
    cout << output << endl; 

    // doesn't work 
    stringstream ss; 
    ss << output; 
    cout << ss.str() << endl; 
} 

我仍然得到令人毛骨悚然的字符。帮帮我!

+0

您需要在合并之前将数字转换为字符串。 'output + = std :: to_string(id)+“\ t”;'。 –

+3

'output + = id +“\ t”;'不符合您的想法。 –

+1

'id +“\ t”'看起来像是一个整数和(会衰减)一个指针,从而导致(可能表现为未定义的行为)指向随机存储器的指针,字符串文字存储在内存中。你可能不想试图将从该内存位置开始的字符串追加到'output'。 – Hurkyl

回答

1
output += id + "\t"; // this is an int 

相当于

output += (id + "\t"); 

这相当于:

char const* s1 = "\t"; 
char const* s2 = s1 + id; 
output += s2; 

除非id10,导致访问,你是不是应该内存,这会导致未定义的行为。

我猜你想要附加id加上"\t"output的字符串表示形式。您可以使用:

output += std::to_string(id); 
output += "\t";