C++ cout funktioniert nicht?
https://i.imgur.com/DP2mOFX.png
Warum funktioniert dieser Code nicht?
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
struct hello
{
std::string one;
std::string two;
int three;
};
hello newhello;
newhello.one = "Hello";
newhello.two = "World";
newhello.three = 1;
std::cout<<newhello.three + newhello.one <<endl;
}
2 Antworten
Vom Fragesteller als hilfreich ausgezeichnet
Von gutefrage auf Grund seines Wissens auf einem Fachgebiet ausgezeichneter Nutzer
programmieren
Das liegt daran, dass es keine Operatorüberladung für + gibt, die int und std::string als Operanden nimmt.
std::cout << newhello.three << newhello.one << std::endl;
sollte funktionieren.
Nachtrag:
Wenn du unbedingt mit + arbeiten willst, dann könntest du etwas in der Art machen:
#include <iostream>
std::string int2str(int i){
if(i==0) return "0";
std::string s;
while(i > 0){
s.insert(0, 1, (char)(i % 10 + '0'));
i /= 10;
}
return s;
}
std::string operator +(int i, const std::string &s){
return int2str(i) + s;
}
std::string operator +(const std::string &s, int i){
return s + int2str(i);
}
int main(){
int i = 123;
std::string s = "foo";
std::cout << i + s << std::endl;
std::cout << s + i << std::endl;
}
Wäre zwar bestenfalls bedingt sinnvoll, würde aber funktionieren.
Ersetze die Zeile ...
std::cout << newhello.three + newhello.one << endl;
... durch ...
std::cout << newhello.three << newhello.one << endl;
Zu dem Rest kann ich nur sagen: Lerne lieber von Anfang an richtig C++. Das erspart dir eine Menge Grübeleien! :)
#include "pch.h"
#include <iostream>
using namespace std;
int main() {
struct hello
{
std::string one;
std::string two;
int three; };
hello newhello;
newhello.one = "Hello"; newhello.two = "World";
newhello.three = 1; std::cout<< newhello.three << newhello.one <<endl; }
Auch so habe ich es nun probiert kriege allerdings immer noch einen Error.