如何在C++中为字符串添加字符?

How to add characters to strings in C++?

本文关键字:字符串 添加 字符 C++      更新时间:2023-10-16

我正在编写一个IP计算器程序,将IP地址转换为广播地址,网络地址等。

我需要先将地址转换为 8 位二进制,我已经使用了itoa十进制到二进制的转换,但我仍然需要使其始终为 8 位。

我想使用switch来做到这一点。首先,程序计算二进制形式的位数,然后使用switch(我把它放在注释中,我需要先弄清楚这个概率(,if它在数字前面添加了足够的零(此时实际上是一个字符串(,所以它总是 8 个字符长。

我想使用string e1('00',e);指令在字符串中添加两个零,但它不起作用。e是原始字符串,e1 是新的 8 个字符的字符串。它不想编译,停在这一行(string e1('00',e);(并给出:

error: no matching function for call to 'std::__cxx11::basic_string<char>::
basic_string(int, std::__cxx11::string)'|

我的代码:

#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
/**
* C++ version 0.4 std::string style "itoa":
* Contributions from Stuart Lowe, Ray-Yuan Sheu,
* Rodrigo de Salvo Braz, Luc Gallant, John Maloney
* and Brian Hunt
*/
std::string itoa(int value, int base)
{
std::string buf;
// check that the base if valid
if (base < 2 || base > 16)
return buf;
enum
{
kMaxDigits = 35
};
buf.reserve(kMaxDigits); // Pre-allocate enough space.
int quotient = value;
// Translating number to string with base:
do
{
buf += "0123456789abcdef"[std::abs(quotient % base)];
quotient /= base;
} while (quotient);
// Append the negative sign
if (value < 0)
buf += '-';
std::reverse(buf.begin(), buf.end());
return buf;
}
int main()
{
cout << "Dzien dobry." << endl
<< "Jest OK!n";
int a, b, c, d, i, j, k, l, m, n, o, p, r, s, t, u, w, v, x, y, z;
cout << "Wprowadz pierwszy oktet: ";
cin >> a;
cout << "Wprowadz drugi oktet: ";
cin >> b;
cout << "Wprowadz trzeci oktet: ";
cin >> c;
cout << "Wprowadz czwarty oktet: ";
cin >> d;
cout << "Wyswietlam adres IP w postaci dziesietnej: " << a << "." << b << "." << c << "." << d << "n";
char res[1000];
itoa(a, res, 2);
string e(res);
itoa(b, res, 2);
string f(res);
itoa(c, res, 2);
string g(res);
itoa(d, res, 2);
string h(res);
//
x = e.size();
cout << x << "n";
/*
if (x<8)
{
switch(x)
{
case 1: string e(1);
break;
case 2: string e(3);
break;
case 3: string e(2);
break;
case 4: string e(0);
break;
case 5: string e(4);
break;
case 6: string e(7);
break;
case 7: string e(0);
break;
default: cout << "error";
}
}
*/
string e1('00', e);
cout << e1 << "n";
cout << "Wyswietlam adres IP w postaci dwojkowej: " << e1 << "." << f << "." << g << "." << h;
return 0;
}

单引号用于单个字符,双引号用于字符串,即多个字符,因此您需要"00".

您提供的参数没有std::string构造函数,除其他方法外,您可以使用:

string e1;
e1.append("00").append(e);

string e1 = "00";
e1 += e;

补充说明:

避免使用#include <bits/stdc++.h>

避免使用using namespace std;

只需使用++=

std::string foo = "Hello";
std::string bar = foo + " world";
std::cout << bar; // Prints Hello world

您还可以使用+=就地修改字符串:

std::string foo = "Hello";
foo += " world"; // foo is "Hello world" now

请注意,这将使您拥有的任何指向foo中字符的现有迭代器无效。您可以通过再次调用beginend来获取新的beginend迭代器。