将std :: string中的子字符串分配给c样式的字符串

时间:2015-11-18 00:18:41

标签: c++ string

我知道有从std :: string转换为c-style的方法,但我遇到的问题是这个错误:     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] != '\0'; len1++)
    {
        num1[len1] = str1[len1] - '0';
    }
    for (len2 = 0; str2[len2] != '\0'; len2++)
    {
        num2[len2] = str2[len2] - '0';
    }
    if (str1 <= 0)
    {
        cout << "Invalid input\n";
    }
    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");
}  

1 个答案:

答案 0 :(得分:1)

我真的怀疑这是你想要做的,但是因为你问过......

您需要执行strcpy

strcpy(str1, str.substr(0, pos).c_str());

查看strcpy的man page / cppreference以了解参数是什么。

更安全可能是使用strncpy,但该功能实际上并不意味着人们使用它。不幸的是,我不相信在C ++或C中实际上有一个标准函数可以执行受长度限制的C风格字符串复制...不安全strcpystrncpy函数的作用很小,但也会查看该文档的文档,因为它实际上意味着完全不同的字符串格式,而不是以null结尾的c风格字符串。

c_str()返回时使用substr可能很诱人,但如果您调用的函数试图存储指向该空间的指针,这可能会很危险。呼叫完成后,substr的返回将被销毁。这会破坏c_str返回。