C ++我可以使用string :: at分配一个int吗?

时间:2015-04-28 14:21:13

标签: c++ string int variable-assignment

在我的代码中我有这个:

int enemyNumber = numberType.at(0);

numberType是一个字符串。

string numberType中的第一个字符是' 1'。但是int enemyNumber在该任务之后变为48。

发生了什么以及如何让敌人成为' 1'?

3 个答案:

答案 0 :(得分:7)

要将具有#include <stdlib.h> #include <string.h> #include <stdio.h> #define INITIAL_SIZE 20 int main( void ) { /** * Allocate space to store a string; the +1 is to make sure * we have space for the 0 terminator. */ char *str1 = calloc( INITIAL_SIZE+1, sizeof *str1 ); size_t str1size = INITIAL_SIZE + 1; /** * str2 will point to a string literal; literals are stored as * arrays of char such that they are allocated at program startup * and held until the program terminates. String literals may * not be modified, so we're declaring the pointer as const char *. */ const char *str2 = " of the Emergency Broadcast System"; /** * Copy a string to that buffer */ strcpy( str1, "This is a test" ); /** * Extend the buffer to hold more stuff; typical strategy is * to double the buffer size each time. For this particular * example this loop should only run once. */ while ( strlen( str1 ) + strlen( str2 ) > str1size) { char *tmp = realloc( str1, 2 * str1size ); if ( !tmp ) { // realloc failed, for this example we treat it as a fatal error exit( -1 ); } str1 = tmp; str1size *= 2; } /** * Append to the buffer */ strcat( str1, str2 ); // do something interesting with str1 here /** * Deallocate the buffer */ free( str1 ); return 0; } '0'的值的单个字符转换为相应的数字,请减去'9'的值:

'0'

如果您想转换包含多个数字的字符串,标准库可以提供帮助:

int enemyNumber = numberType.at(0) - '0';

答案 1 :(得分:6)

这是因为48是#include <QtCore/QDebug> #include "pinger.h" Pinger::Pinger(): _pingUrl("8.8.8.8") { } Pinger::~Pinger() { } void Pinger::startPingCheck(const QString& urlToPing, const int& pingInterval) { _pingUrl = urlToPing; // Listen for messages from the ping process connect(&_pingProcess, SIGNAL(readyRead()), this, SLOT(_handleProcessMessage())); // Connect the timer to the exec method that actually calls the ping process _pingTimer.setInterval(pingInterval * 1000); _pingTimer.setSingleShot(false); connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(_pingExec())); _pingTimer.start(); } void Pinger::_pingExec() { QStringList arguments; arguments << "-n" << "1" << _pingUrl; _pingProcess.start("ping", arguments); } void Pinger::_handleProcessMessage() { QByteArray response = _pingProcess.readAll(); QString responseStr(response); if(responseStr.contains("100% loss")) { qDebug() << "Ping failed. " << _pingUrl << " down."; emit pingFailed(); } } 的字符代码。要获取整数值,请推导出类似1的{​​{1}}。这样,您将获得'0'的字符代码减去int enemyNumber = numberType.at(0) - '0';的字符代码,即'1'。这适用于所有数字,因为它们的字符代码是连续数字。

答案 2 :(得分:1)

如果要保留在字符串对象中,可以执行以下操作:

#include <string>
#include <iostream>

int main()
{
    std::string numberType("1234");
    const int enemyNumber = std::stoi( numberType.substr(0,1) );

    std::cout << enemyNumber;
    return 0;
}

stoi()将为您执行从string到int的转换。