2016-04-18 3 views
2

Я разрабатываю проект на своей плате arduino, для моей проекции идеи я написал код в C++. Но некоторые файлы и функции библиотеки не были найдены на IDE arduino, которые, как мне известно, находятся в C++.Преобразование кода на C++ в arduino с файлами и функциями заголовка строки и потока

Я прилагаю код ниже. Я хочу преобразовать весь код в arduino, в котором только convertToEnglish останется как функция в arduino. Я попытался заменить файлы заголовков и другие функции на библиотеку строк и другой файл заголовка Stream.h, но почти все оказалось напрасно. Следовательно, чтобы превысить это, пожалуйста, укажите мне решение. Я пробовал использовать Standard c++ в качестве цитаты, но все же функция getline fucntion сообщает об ошибке, указывающей, что cin не был объявлен в области видимости.

#include <StandardCplusplus.h> 
#include <system_configuration.h> 
#include <unwind-cxx.h> 
#include <utility.h> 



#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std; 

string convertToEnglish(string morse, string const morseCode[]); 

int main() 
{ 
string input = ""; 
cout << "Please enter a string in morse code: "; 
getline(cin, input); 

string const morseCode[] = {".-", "-...", "-.-.", "-..", ".", "..-.", 
"--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", 
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; 

cout << convertToEnglish(input, morseCode) << endl; 


return 0; 
} 

string convertToEnglish(string morse, string const morseCode[]) 
{ 
string output = ""; 
string currentLetter = ""; 
istringstream ss(morse); 

size_t const characters = 26; 

while(ss >> currentLetter) 
{ 
    size_t index = 0; 
    while(currentLetter != morseCode[index] && index < characters) 
    { 
     ++index; //increment here so we don't have to decrement after the loop like if we put in the condition 
    } 

    output += 'A' + index; 
} 

return output; 
} 

сообщение об ошибке: Arduino: 1.6.8 (Windows 8.1), Совет: "Arduino/Genuino Uno"

E: \ мозг \ Arduino \ sketch_mar15a \ Blink \ Blink \ Blink.ino: в функции 'INT Main()':

моргания: 19: ошибка: 'CIN' не был объявлен в этой области

getline(cin, input); 

     ^

статус выхода 1 'CIN' не был объявлен в этой области

Этот отчет будет содержать более подробную информацию с «Показывать подробный вывод во время компиляции». опция включена в файле -> Настройки.

+1

В чем проблема? – SergeyA

+0

Строковые и sstream файлы заголовков не могут быть найдены в arduino ide. Если не ват - другие файлы заголовков, которые нужно использовать для получения того же выхода – SathyaNarayanan

+0

Возможный дубликат [Векторы в Arduino] (http://stackoverflow.com/questions/9986591/vectors-in-arduino) – willll

ответ

0

Непонятно, для меня, что вы можете использовать и что вы не можете.

Предположив, что вы не можете использовать std::vector, но вы можете использовать старую добрую C строку (символ *) функция и функции ввода/вывода, я подготовил пример

#include <cstdio> 
#include <cstdlib> 
#include <iostream> 
#include <stdexcept> 


char * convertToEnglish (char *      output, 
         std::size_t     dimOut, 
         char const * const   input, 
         char const * const * const morseCode, 
         std::size_t     numMorseCodes) 
{ 
    if ((nullptr == output) || (0U == dimOut) || (nullptr == input) 
     || (nullptr == morseCode) || (0U == numMorseCodes)) 
     throw std::runtime_error("invalid input in cTE()"); 

    std::size_t posOut = 0U; 
    std::size_t index; 
    char const * ptrI0; 
    char const * ptrI1; 
    char   currentLetter[5]; 

    std::memset(output, 0, dimOut); 

    for (ptrI0 = input ; nullptr != ptrI0 ; ptrI0 = ptrI1) 
    { 
     ptrI1 = std::strpbrk(ptrI0, " \n"); 

     if (nullptr == ptrI1) 
     { 
     // last character if the string isn't cr terminated 
     if (sizeof(currentLetter) <= strlen(ptrI0)) 
      throw std::runtime_error("to length last char in cTE()"); 

     std::strcpy(currentLetter, ptrI0); 
     } 
     else 
     { 
     if (sizeof(currentLetter) <= (ptrI1 - ptrI0)) 
      throw std::runtime_error("to length char in cTE()"); 

     std::memset(currentLetter, 0, sizeof(currentLetter)); 
     std::strncpy(currentLetter, ptrI0, (ptrI1 - ptrI0)); 

     if ('\n' == *ptrI1) 
      ptrI1 = nullptr; 
     else 
      ++ptrI1; 
     } 

     for (index = 0U 
      ; (index < numMorseCodes) 
      && strcmp(currentLetter, morseCode[index]) 
      ; ++index) 
     ; 

     if (numMorseCodes <= index) 
     throw std::runtime_error("no morse code in cTE()"); 

     output[posOut] = 'A' + index; 

     if (++posOut >= dimOut) 
     throw std::runtime_error("small out buffer in cTE()"); 
    } 

    return output; 
} 


int main() 
{ 
    constexpr char const * morseCode[] = {".-", "-...", "-.-.", 
     "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", 
     "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", 
     "...-", ".--", "-..-", "-.--", "--.."}; 

    constexpr std::size_t numMorseCodes 
     = sizeof(morseCode)/sizeof(morseCode[0]); 

    char *  input = nullptr; 
    std::size_t dim = 0U; 

    if (getline(&input, &dim, stdin) == -1) 
     throw std::runtime_error("error reading input"); 

    char output[1024]; 

    std::cout << convertToEnglish(output, sizeof(output), input, 
           morseCode, numMorseCodes) << std::endl; 

    return EXIT_SUCCESS; 
} 

следующего C-стиль, если вы можете использовать std::vector или std::string, можно сделать действительно проще.

p.s .: извините за мой плохой английский