简体   繁体   English

如何在 C++ 中将变量结果插入到字符串中

[英]How do I insert a variable result into a string in C++

I just started learning C++ in Qt and I was wondering how can I put a variables result in a string?我刚开始在 Qt 中学习 C++,我想知道如何将变量结果放入字符串中? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence.我试图将它用于一个简单的应用程序,其中有人将他们的名字放在一个文本字段中,然后按下一个按钮,它会在一个句子中显示该名字。 I know in objective-c it would be like,我知道在objective-c中它会像,

NSString *name = [NSString stringWithFormatting:@"Hello, %@", [nameField stringValue]];
[nameField setStringValue:name];

How would I go about doing something like this with C++?我将如何用 C++ 做这样的事情? Thanks for the help谢谢您的帮助

I assume we're talking about Qt's QString class here.我假设我们在这里谈论的是 Qt 的QString类。 In this case, you can use the arg method:在这种情况下,您可以使用arg方法:

 int     i;           // current file's number
 long    total;       // number of files to process
 QString fileName;    // current file's name

 QString status = QString("Processing file %1 of %2: %3")
                 .arg(i).arg(total).arg(fileName);

See the QString documentation for more details about the many overloads of the arg method.有关arg方法的许多重载的更多详细信息,请参阅QString 文档

You don´t mention what type your string is.你没有提到你的字符串是什么类型。 If you are using the standard library then it would be something along the lines of如果您使用的是标准库,那么它将类似于

std::string name = "Hello, " + nameField;

That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:这适用于连接字符串,如果你想插入其他复杂类型,你可以使用这样的字符串流:

std::ostringstream stream;
stream << "Hello, " << nameField;
stream << ", here is an int " << 7;

std::string text = stream.str();

Qt probably has its own string types, which should work in a similar fashion. Qt 可能有自己的字符串类型,应该以类似的方式工作。

I would use a stringstream but I'm not 100% sure how that fits into your NSString case...我会使用stringstream但我不是 100% 确定它如何适合您的 NSString 案例......

stringstream ss (stringstream::in);
ss << "hello my name is " << nameField;

I think QString has some nifty helpers that might do the same thing...我认为QString有一些漂亮的助手可以做同样的事情......

QString hello("hello ");
QString message =  hello % nameField;

You could use QString::sprintf .您可以使用QString::sprintf I haven't found a good example of it's use yet, though.不过,我还没有找到使用它的好例子。 (If someone else finds one, feel free to edit it in to this answer). (如果其他人找到了,请随时将其编辑到此答案中)。

You might be interested in seeing information about the difference between QString::sprintf and QString::arg .您可能有兴趣查看有关QString::sprintfQString::arg之间差异的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM