正在将std::string中的子字符串赋值为c样式字符串
Assiging sub string from std::string to a c-style string
我知道有一些方法可以将std::string转换为c样式,但我遇到的问题是这个错误:4 IntelliSense:表达式必须是可修改的左值有人能告诉我问题出在哪里吗?此外,你能澄清一下如何有效地转换为c样式字符串,并在这种特殊情况下分配它吗?
谢谢
#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
using namespace std;
class Addition
{
private:
int num1[255], num2[255], sum[255];
char str1[255], str2[255];
string str;
int len1, len2;
public:
Addition(){};
void m_add();
};
void Addition::m_add()
{
scanf("%s", str);
int pos = find(str[0], str[255], ' ');
&str1 = str.substr(0, pos);
&str2 = str.substr(++pos);
//scanf("%s", &str1);
//scanf("%s", &str2);
/*convert from a character to an int*/
for (len1 = 0; str1[len1] != ' '; len1++)
{
num1[len1] = str1[len1] - '0';
}
for (len2 = 0; str2[len2] != ' '; len2++)
{
num2[len2] = str2[len2] - '0';
}
if (str1 <= 0)
{
cout << "Invalid inputn";
}
int carry = 0;
int k = 0; //keeps track of index loop stopped at
//start adding from the end of the array
int idx1 = len1 - 1;
int idx2 = len2 - 1;
//adds only for the size of teh smallest array
for (; idx1 >= 0 && idx2 >= 0; idx1--, idx2--, k++)
{
//we will have to read values stored in sum in reversed order
sum[k] = (num1[idx1] + num2[idx2] + carry) % 10;
//using truncation to our benefit
//carry over can only ever be one thats why we use /10 not %10
carry = (num1[idx1] + num2[idx2] + carry) / 10;
}
/*takes care of the digits not added to sum from bigger array*/
//if the first array is bigger...
if (len1 > len2)
{
while (idx1 >= 0){
sum[k++] = (num1[idx1] + carry) % 10;
carry = (num1[idx1--] + carry) / 10;
}
}
//if the second array is bigger
else if (len1 < len2)
{
while (idx2 >= 0){
sum[k++] = (num2[idx2] + carry) % 10;
carry = (num2[idx2--] + carry) / 10;
}
}
//that you have a carry ove to the very end of the number
if (carry != 0){
sum[k++] = carry;
}
cout << "sum = ";
//print out digits in 'sum' array from back to front
for (k--; k >= 0; k--)
{
cout << sum[k];
}
cout << 'n';
}
int main(){
Addition inst1;
int n;
cin >> n;
for (int i = 0; i <= n; i++){
inst1.m_add();
}
system("pause");
}
我真的怀疑这是你真正想做的,但既然你问。。。
你需要做一个strcpy
:
strcpy(str1, str.substr(0, pos).c_str());
查看strcpy的手册页/cppreference,了解参数是什么。
使用strncpy
可能更安全,但该功能实际上并不是为了做人们使用它的事情。不幸的是,我不相信C++或C中真的有一个标准函数可以复制受长度限制的C风格字符串。。。没有安全的CCD_ 3。strncpy
函数在必要时也会这样做,但也要查看该函数的文档,因为它实际上适用于与以null结尾的c样式字符串完全不同的字符串格式。
在substr
返回中使用c_str()
可能很诱人,但如果您调用的函数试图存储指向该空间的指针,则这可能很危险。调用完成后,substr
的返回将被销毁。这将破坏c_str
返回。
相关文章:
- 如何使用向量为字符串赋值
- 避免在 ctor 初始值设定项列表中的字符串赋值中使用双重调用函数
- 无法为字符串赋值(Eclipse CDT、MinGW、C++)
- 带有初始值设定项列表的字符串赋值
- R 值重载运算符字符串赋值错误
- 使用for循环的C字符串赋值
- 正在将std::string中的子字符串赋值为c样式字符串
- 字符串赋值中的代码转储
- 当我们可以使用=运算符为字符串赋值时,为什么要在赋值之前使用new运算符为字符串动态分配内存
- 析构函数忽略字符串赋值
- 如果右手边包含字符串文字的串联,则C++const std::字符串赋值错误
- 在c++中如何从另一个字符串赋值未初始化的字符串值
- 字符串赋值错误
- 蠢Q:将字符串赋值到字符数组中
- 如何将字符串赋值为十六进制
- 字符串赋值差异
- std::通过索引进行字符串赋值似乎不起作用
- 当常量字符串赋值给常量字符指针时会发生什么?
- 字符串赋值中的Coredump
- 这里面有什么错误?字符串赋值